Perl Functions
Defining Functions sub subroutine_name { stmt1; stmt2; … } Arguments are not listed in declaration May use a return statement If no return statement, value of last expression is returned Can return scalar, array, or hash
Calling Functions Called by sub_name(arg1, arg2, …); Parens may be omitted if declaration has already been seen Arguments are available in called function as entries in array @_
Sample Function sub max { ($a, $b) = @_; $a > $b ? $a : $b; } Puts args into variables Returns larger if they are numbers
Array and Hash Arguments Can only pass one array or hash as an argument unless you know the size Args are flattened (@a, @b) = @_; #all in @a Can precede array or hash by a fixed number of scalars but ($a, @b, $c) = @_; won’t work
Scope my($a); my $c, @e; Declares local variable with scope of block (including function) or loop (in control Parentheses are optional
Strict use strict; Directive requires Declare all variables Declare all functions before first use