Parrot: Tutorial 1

Last modification: 2008/07/20 23:55

Tutorial 1: Variables

Registers

The most basic kind of variable in Parrot is the register. Registers can be one of four types: integer, float, string, or pmc, and are represented as follows:

.sub vars set I1, 1 # integer set N1, 2.3 # float set S1, "hi" # string set P1, .Integer # pmc: A Parrot Magic Cookie .end

Don't worry about the 'pmc' type for now. Hopefully the other types are self-explanatory!

The above code is both valid PASM (assembly) and PIR. If you've ever programmed in assembly language, this should look very familiar. PIR also allows syntax that is more acceptable to people used to higher level languages:

.sub vars I1 = 1 # integer N1 = 2.3 # float S1 = "hi" # string .end

However, this syntax accesses Parrot's registers directly. This means that if you ever assign a value to, for example, S10, you will have to manually check each line of your code to make sure its value isn't accidentally overwritten anywhere else, for example, if you call another subroutine.

You are also limited to just 99 registers of each type, so scope collision is going to be a problem sooner or later.

Virtual Registers

To bypass these problems, PIR introduces a neat trick: virtual registers. You can use an infinite number of virtual registers without fear of accidentally overwriting them in a separate subroutine, simply by pre-pending your register with a $:

.sub vars2 set I0, 10 set $I0, 20 # I0 is still 10; # Parrot detects I0 is in use and routes $I0 somewhere safe set $I100, 1 # note using 'I100' would cause an error print $100 .end

Local Variables

Even this isn't very user friendly, so Parrot also has locally named variables:

.sub life .local int firstnum .local int secondnum .local int result .local string ans ans = "The answer is " firstnum = 17 secondnum = 25 result = firstnum + secondnum print ans print result .end

You will notice the use of 'int' for an integer, and 'string' for a string. Other valid .local options are:

.local num a_float # a floating point number .local int first, second, result # can declare multiple vars of # the same type on one line

Constants

Constants are just like local variables, except that a value is assigned for them as they are declared. After declaration constant values cannot be modified.

.const int the_answer = 42 # integer constant .const string mouse = "Mouse" # string constant

Remember that all of these shortcuts compile down to PASM and then to Parrot bytecode when you run the program. If you want to see the PASM that corresponds to a given PIR file, just run:

$ parrot -o- file.pir