O'Reilly logo

Perl 6 Essentials by Leopold Tötsch, Dan Sugalski, Allison Randal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Subroutines

A calculation like “the factorial of a number” may be used several times in a large program. Subroutines allow this kind of functionality to be abstracted into a unit. It’s a benefit for code reuse and generally makes it easier to work with the code too. Even though PASM is just an assembly language running on a virtual processor, it has a number of features to support high-level subroutine calls. IMCC offers a smoother interface to those features.

Stack-Based Subroutine Calls

Unlike most high-level languages, PIR and PASM don’t provide a single statement to call a subroutine, pass in the arguments, and return the result. This is a language designed to implement other languages, and every language does subroutine calls a little differently. What’s needed is a set of building blocks and tools, not a prepackaged solution.

PIR has several directives and instructions relevant to subroutine calls. The most important is call , which simply branches to a subroutine label. On the side of the caller, .arg passes an argument to a subroutine, and .result retrieves a result. Within the subroutine, .param retrieves an argument passed to the subroutine, and .return returns a value to the caller:

.sub _main .local int counter counter = 5 .arg counter # pass an argument call _fact # call the subroutine .local int product .result product # retrieve the result print product print "\n" end .end .sub _fact saveall # save caller's registers .param int N # retrieve the parameter .local ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required