|
How To Write A PERL
Program
Now we want to call a
subroutine. Even if you have never written a program you have
heard the term "subroutine" on almost every TV show and
movie. It is a real term and it does mean something in programing.
In perl it is a sub section
that is defined and can be called if and when you want it.
The subroutines are defined as;
sub myfirstsubroutine { }
What every we put inside the
braces { } will only run when we ask it to by calling the
subroutine. Subroutines can be called serveral different ways,
but here we try to stick with one basic call. Using &subname;
Subroutines must be
added at the end of the program. Such as:
#!/usr/bin/perl
$ourfirstvarriable = localtime;
print "Content-type: text/html\n\n";
print "This is our first perl program. The time is $ourfirstvarriable";
sub myfirstsubroutine
{ }
To use the subroutine in the
program we need it to do something, like print an extra line or
run a function. In this case, we just want to show it working, so
we will print "Testing Subroutine".
just add in the print command
and the text as we have done previously.
sub myfirstsubroutine
{ print "Testing Subroutine"; }
Now we can add it to our
program and call the sub where we want the line to print.
#!/usr/bin/perl
$ourfirstvarriable = localtime;
print "Content-type: text/html\n\n";
&myfirstsubroutine;
print "This is our first perl program. The time is $ourfirstvarriable";
sub
myfirstsubroutine { print "Testing Subroutine<br>";
}
Even though we added the sub at the end of
the program it is called before we print the first line and the
new first line will be Testing Subroutine.
The subroutine is very helpful when we want
the program to decide if and when to use the subroutine. lets say,
we only want the message to appear on Monday. We can ise an
"if" statement to only call the sub if it is monday.
Using the localtime we can look for the Mon
in the localtime string and only run the sub if the there is a
match.
We replace &myfirstsubroutine;
with:
if (localtime =~ /mon/i){&myfirstsubroutine;}
Then the testing subroutine text will ony
appear on Mondays.
That is the basics of subroutines and the
print commands. Even with this very basic knowledge, you can
write your own program. On the next page we will discuss some of
the basic math functions.
PREVIOUS << >> NEXT
|