Parrot: Tutorial 2

Last modification: 2008/07/20 23:55

Tutorial 2: Branch Control

PIR includes basic branch control to construct logical tests:

# If-Then
.sub test .local int i i = 5 if i > 8 goto skip print "in range\n" skip: .end

# If-Then-Else
.sub test2 .local int i i = 5 unless i <= 8 goto cond_false # 'unless x' is equivalent to 'if not x' print "in range\n" goto endif cond_false: print "out of range\n" endif: .end

# While Loop
.sub sum # State the number of squares to sum. .local int minnum, maxnum minnum = 1 maxnum = 3 # We'll use some named registers. Note that we can declare many # registers of the same type on one line. .local int i, total total = 0 # Loop to do the sum. i = minnum loop: total += i inc i if i <= maxnum goto loop # Output result. print "Sum of " print minnum print ".." print maxnum print " is: " print total print "\n" .end