Lexicals and Globals

So far, we’ve been treating Parrot registers like the variables of a high-level language. This is fine, as far as it goes, but it isn’t the full picture. The dynamic nature and introspective features of languages like Perl make it desirable to manipulate variables by name, instead of just by register or stack location. These languages also have global variables, which are visible throughout the entire program. Storing a global variable in a register would either tie up that register for the life of the program or require unwieldy manipulation of the user stack.

Parrot provides structures for storing both global and lexically scoped named variables. Lexical and global variables must be PMC values. PASM provides instructions for storing and retrieving variables from these structures so the PASM opcodes can operate on their values.

Globals

Global variables are stored in a PerlHash, so every variable name must be unique. PASM has two opcodes for globals, store_global and find_global:

new P10, .PerlInt
set P10, 42
store_global "$foo", P10
# ...
find_global P0, "$foo"
print P0                        # prints 42
end

The first two statements create a PerlInt in the PMC register P10 and give it the value 42.

The store_global opcode only stores a reference to the object. If we add an increment statement:

inc P10

after the store_global it increments the stored global printing 43. If that’s not what you want, you can clone the PMC before you store it. It does have advantages, though. If you retrieve ...

Get Perl 6 Essentials now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.