9.11 Loading Bytecode

     

In addition to running Parrot bytecode on the command line, you can also load precompiled bytecode directly into your PASM source file. The load_bytecode opcode takes a single argument: the name of the bytecode file to load. So, if you create a file named file.pasm containing a single subroutine:

 # file.pasm .pcc_sub _sub2:               # .pcc_sub stores a global sub    print "in sub2\n"    invoke P1 

and compile it to bytecode using the -o command-line switch:

 $ parrot -o file.pbc file.pasm 

You can then load the compiled bytecode into main.pasm and directly call the subroutine defined in file.pasm :

 # main.pasm _main:   load_bytecode "file.pbc"    # compiled file.pasm   find_global P0, "_sub2"   invokecc   end 

The load_bytecode opcode also works with source files, as long as Parrot has a compiler registered for that type of file:

 # main2.pasm _main:   load_bytecode "file.pasm"  # PASM source code   find_global P0, "_sub2"   invokecc   end 

Subroutines marked with @LOAD run as soon as they're loaded (before load_bytecode returns), rather than waiting to be called. A subroutine marked with @MAIN will always run first, no matter what name you give it or where you define it in the file.

 # file3.pasm .pcc_sub @LOAD _entry:        # mark the sub as to be run   print "file3\n"   invoke P1                   # return # main3.pasm _first:                       # first is never invoked   print "never\n"   invoke P1 .pcc_sub @MAIN _main:         # because _main is marked as the   print "main\n"              # MAIN entry of program execution   load_bytecode "file3.pasm"   print "back\n"   end 

This example uses both @LOAD and @MAIN . Because the _main subroutine is defined with @MAIN it will execute first even though another subroutine comes before it in the file. _main prints a line, loads the PASM source file, and then prints another line. Because _entry in file3.pasm is marked with @LOAD it runs before load_bytecode returns, so the final output is:

 main file3 back 



Perl 6 and Parrot Essentials
Perl 6 and Parrot Essentials, Second Edition
ISBN: 059600737X
EAN: 2147483647
Year: 2003
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net