#!C:/perl/bin/perl.exe use CGI::Carp qw(fatalsToBrowser); use CGI; $query = new CGI; print $query->header; print $query->start_html(-title=>'Subroutines'); print ""; # ----------------------------------------- print "Results of first subroutine:
"; &printText2("The subroutine will format this text with a large font size."); # ----------------------------------------- print "

Results of second subroutine:
"; &printText3("The subroutine will format this text with a specified font size.", 1); # ----------------------------------------- print "

Results of third subroutine:
"; $sum = &sumNumbers1(1,2,3,4,5,6,7,8); print "The sum of those numbers is $sum.
"; # or, using an array as a parameter: @numbers = (1,1,1,1,1,1,1); $sum = &sumNumbers1(@numbers); print "The sum of those numbers is $sum.
"; print $query->end_html; # ----------------- Subroutines ----------------------------- # for a good tutorial/overview of Perl subroutines, see # http://www.comp.leeds.ac.uk/Perl/subroutines.html #------------------------------------------------------------ # This subroutine accepts parameters # When the subroutine is called any parameters are passed as a list in the special @_ list array variable. sub printText2 { print " @_
"; } # This subroutine accepts more than 1 parameter # When the subroutine is called any parameters are passed as a list in the special @_ list array variable. # each parameter can be referenced via $_[0] (first parameter) and $_[1] (second parameter) sub printText3 { # 0th parameter is text to be displayed $_[0] # 1st parameter is font size $_[1] print " $_[0]
"; } # This subroutine accepts more than 1 parameter # However, this subroutine does not assume how many variables are being passed to it and uses # the for loop to parse each parameter # This example also illustrates how values can be *returned* by a subroutine # (Note the difference in class between local and global variables.) sub sumNumbers1 { $nItems = @_; # assigns the length of the array to the variable $nItems $sum = 0; for($i=0;$i<=($nItems-1);++$i){ $sum = $sum + $_[$i]; } return $sum; }