Complete Example
Notice in the following example the subs are located after the printing of the HTML closing tag. You can put them in a library but when I put them as part of a called page, I like to put them at the end.
#!/usr/local/bin/perl -w
print("Content-type: text/html\n\n");
#Start of HTML page.
print("<html>");
print("<head><title>Perl Tutorial</title></head>");
print("<body>");
&sayHello("Mike");
print("<br>");
#Example 1
$x = &add(2,1);
print("2+1=$x.<br>");
#Example 2 - no parens
$x = &add(2,2);
print "2+2=$x.<br>";
#Example 3 - parens with . concatenation operator
$x = &add(2,3);
print("2+3=" . $x . ".<br>");
#Example 4 - using sub directly
print("2+4=" . &add(2,4) . ".<br>");
print("</body></html>");
#
# Subs
#
sub sayHello {
my ($pName) = $_[0];
print("Hello $pName!");
}
sub add {
my ($p1) = $_[0];
my ($p2) = $_[1];
return $p1 + $p2;
}