main
December 19th, 2024    

CIS 2.55
Main
Files
Syllabus
Overview
Links
Homeworks

UPLOAD HOMEWORKS

Notes
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
Bayes (src)

Tests
Sample Midterm
Sample Final

Misc
Arithmetics
Fourier Mult

Notes 0008

Subroutines

Read Chapter 6 of Programming Perl.

Perl provides for user defined subroutines, which are basically reusable blocks of code which you can call from various places. Unlike other languages however, you can also have references to subroutines, and pass them around as arguments to other subroutines.

The basic syntax is:

sub NAME {
 ...
}

Where NAME is whatever name you decide to give to the subroutine.

Inside the subroutine, the parameters are located in the @_ array. First thing in that list is the first parameter, etc.

Very often, you retrieve parameters by just assigning the array to another array declared inside the subroutine. For example:

sub foo {
    my ($one,$two,$three) = @_;
    print "$one, $two $three\n";
}

The function above displays the first three parameters that it receives. Note that I said "first three." The function can actually receive more (or less), but it will only care about the first three (if there are less parameters, the other values will be undefined).

That's about it for the basic use of subroutines. Reach chapter 6 for more advanced (and equally useful) ways to work with subroutines.



































© 2006, Particle