#Function - grouping of code, called by name, do some work, return some value #User-defined functions => subroutines in Perl countdown(); #call function below print "Blastoff!\n"; &countdown(); #call function below, different syntax print "Blastoff!\n"; sub countdown{ for ($i=10; $i>=0; $i--) { print "$i -"; } } ###################################################### #perl subroutine can be called anywhere in the program sub world{ print "World!\n"; } sub hello{ print "Hello, "; world(); #call subroutine above } hello(); ###################################################### #returning values from subroutine sub two_by_four{ return 2*4; # 2*4; #strange, both works } print 8*two_by_four()."\n"; ###################################################### #returning values from subroutine sub x_greaterthan100 { #relies on the value of $x being set elsewhere if ($x>100) { return 1; #value for true } else { return 0; } } $x = 70; if (x_greaterthan100()) { print "$x is greater than 100\n"; } else { print "$x is NOT greater than 100\n"; } ###################################################### #returning arrays/hashes from subroutine sub shift_to_uppercase { @words = qw (cia fbi un nato unicef); foreach (@words) { $_ = uc($_); } return @words; } @acronyms = shift_to_uppercase(); print join(', ', @acronyms)."\n"; #output a string, connect all element of array, with "," ###################################################### #arguments, access through special variable @_, an array sub printargs { print join (", ", @_); } printargs('market', 'home' , 10, 20); print "\n"; sub print_3rd_argument { print $_[2]; #third element of array } print_3rd_argument('market', 'home' , 10, 20); print "\n"; sub display_box_score { ($num_hits, $num_at_bats) = @_; print "For $num_at_bats trips to the plate, "; print "he's hitting ", $num_hits/$num_at_bats,"\n"; } display_box_score(50, 210); #passing hashes and arrays sub sort_numerically { print "Sorting ..."; return (sort {$a<=>$b} @_); # {$a<=>$b} sort numerically ascending # refer to documentation for sort syntax } @items = (10, 12, 5, 15, 14); @sorted_items = sort_numerically(@items); print join(",", @sorted_items); print "\n"; #note: passing 2 or more hashes or arrays does not work #2 arrays are join to one array, not an array of arrays #pass in scalar and array sub updated_sort_numerically { ($message, @myarray) = @_; print "$message ..."; return (sort {$a<=>$b} @myarray); # {$a<=>$b} sort numerically ascending # refer to documentation for sort syntax } @sorted_items = updated_sort_numerically("Welcome! ",@items); print join(",", @sorted_items); print "\n"; ###################################################### #use "my" operator to delcare variables private to a subroutine sub myfunc{ my $x; $x=20; print "$x\n"; #this is a private $x } $x=10; #this is a global $x print "$x\n"; myfunc(); print "$x\n";