Cyber Sentry
Applications Development
System Architecure Design
Technical Due Diligence
Qmail Support and Consultancy
Partners
Client Testimonials
Help Sections
Community Sponsorship
Software Patents
Site Map
Contact us
Home
 
Home

Subroutines

Like any good programming langauge Perl allows the user to define their own functions, called subroutines. They may be placed anywhere in your program but it's probably best to put them all at the beginning or all at the end. A subroutine has the form

 

sub mysubroutine

{

print "Not a very interesting routine\n";

print "This does the same thing every time\n";

}

 

regardless of any parameters that we may want to pass to it. All of the following will work to call this subroutine. Notice that a subroutine is called with an & character in front of the name:

 

&mysubroutine; # Call the subroutine

&mysubroutine($_); # Call it with a parameter

&mysubroutine(1+2, $_); # Call it with two parameters

 

Parameters

In the above case the parameters are acceptable but ignored. When the subroutine is called any parameters are passed as a list in the special @_ list array variable. This variable has absolutely nothing to do with the $_ scalar variable. The following subroutine merely prints out the list that it was called with. It is followed by a couple of examples of its use.

 

sub printargs

{

print "@_\n";

}

 

&printargs("perly", "king"); # Example prints "perly king"

&printargs("frog", "and", "toad"); # Prints "frog and toad"

 

Just like any other list array the individual elements of @_ can be accessed with the square bracket notation:

 

sub printfirsttwo

{

print "Your first argument was $_[0]\n";

print "and $_[1] was your second\n";

}

 

Again it should be stressed that the indexed scalars $_[0] and $_[1] and so on have nothing to with the scalar $_ which can also be used without fear of a clash.



Qmail Help Section
Perl Tutorial
Top top Copyright Cyber Sentry Ltd  

Cyber Sentry -- Application Development Sitemap 1 2 3