The keyword sub is used to define a procedure. Procedures are called with an & in front of their name. This example shows a procedure named &arrayprint that prints the contents of the array @data with one element on each line:
sub arrayprint { print "$_\n" foreach (@data); } @data = (0..9); &arrayprint;
Notice that @data has been declared without the keyword my, so it is a global variable. This allows the procedure to use @data. A better way to write this procedure would be to make @data a local variable and pass it to the procedure as an argument.
Variables passed to a procedure are stored in the array @_. In this example, the value of $n will be sent to &arrayprint as the first element in @_:
sub factorial { my $x = shift(@_) ; my $fact = 1 ; $fact *= $_ foreach (1..$x) ; print "$x factorial is $fact.\n"; } chomp (my $n = <STDIN>); &factorial ($n) ;
You can get values back from a procedure, as well. By default, the procedure returns the value of the last statement. You can also use the keyword return to immediately exit the procedure and return a value:
sub pythagorean { ($x, $y) = @_; if (! defined $x || ! defined $y) { # check that the input is defined return 0; # and return 0 if it isn't } ($x**2 + $y**2) ** .5; } print "&pythagorean (3, 4) \n";