Subroutines

Domain Hosting image
Web Hosting
Dedicated server
ssl certificate
Web Design image
Email

The main purpose of subroutines is to consolidate repeated sets of statements into a single block. This has the following advantages:

If we want later to change the block of lines, we can do it in just one place instead of having to search the program for all places where the set of lines appears.

Our program will be shorter and will thus run faster

In long programs, subroutines can act like named "subprograms" to help us organise our program

For example, imagine a program that has a dozen or so arrays, and at different points in the program we want to print just the last item in each list (array) and put a copy of that item into @big. Without subroutines it might look like this:

.... print("Price:$List[$List]);
push(@Big, $List[$#List]);
....
print("Price:$Cus[$Cust]);
push(@Big, $Cust[$#Cust]);
With subroutines it might look like this;
sub PrintBig{
@thelist=@_;
print("Price:$thelist[$thelist);
push(@Big, $thelist[$#thelist]);
}
...
&PrintBig(@List);
...
&PrintBig(@Cust);

The parts of a subroutine
The sub statement has this format:
sub NAME (BLOCK)

To call a subroutine, you use the ampersand (@) character followed by the subroutine name. If the subroutine takes arguments, you include those in parentheses just like we do for Perl's built in functions. Perl makes the argument called available in the special list @_ In the preceding example, the argument was a list, so @_ is a entire list.

It is also common to have one or two arguments that are scalars. In this case, we can use shift function to get the arguments out of the @_ list in the order they went in.

Eg.: sub Add(
$a = shift(@ );
$b = shift(@ );
return ($a +$b);

Perl creates the variable $a to hold the first argument and $b to hold the second argument. The return function is the most common way to return a value. We can return either a scalar or a list.



Domain Name Search

www.


Copyright (C) 2007. Web Domain design hosting. All rights reserved.