Sunday, May 12, 2013
Perl Scripting - Part 3
Please click here for part-2
-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:
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
-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.
&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:
print "Your first argument was $_\n";
print "and $_ was your second\n";
-Again it should be stressed that the indexed scalars $_ and $_ and so on have nothing to with the scalar $_ which can also be used without fear of a clash.
-Result of a subroutine is always the last thing evaluated.
-This subroutine returns the maximum of two input parameters.
An example of its use follows.
if ($_ > $_)
$biggest = &maximum(37, 24); # Now $biggest is 37
-The &printfirsttwo subroutine above also returns a value, in this case 1. This is because the last thing that subroutine did was a print statement and the result of a successful print statement is always 1.
-The @_ variable is local to the current subroutine, and so of course are $_, $_, $_, and so on.
-Other variables can be made local too, and this is useful if we want to start altering the input parameters.
-The following subroutine tests to see if one string is inside another, spaces not withstanding.
An example follows.
local($a, $b); # Make local variables
($a, $b) = ($_, $_); # Assign values
$a =~ s/ //g; # Strip spaces from
$b =~ s/ //g; # local variables
$a = $b;
$b = $a; = What result they will be?
# $a = $_;
# $b = $_;
print "the first element is: $a\n";
print "the second element is: $b\n";
&inside("lemon", "dole money");
Please click here for perl practicals - Lab1