Subroutine

what is subroutine?
Subroutines are the basic computer science methodology to divide tasks into subtasks.

Example:

sub version {
print “version of pl file.”;
}

It can be call by name without braces, but make sure subroutine defined before we use them

Example:

mysub;

sub mysub {
print “mysub is called”;
}

# Following error comes if sub routine is called without braces

# Unquoted string “mysub” may clash with future reserved word at t.pl line 4.
# Useless use of a constant (mysub) in void context at t.pl line 4.

Parameters & Arguments

@_ is the list of incoming parameters to a sub.
$_ is known as the “default input and pattern matching space

sub mysub {
foreach(@_) {
print $_;
}
}
myspace(1,2,3);

Return

By default (implicitly) last statement of sub routine returns
Programmer must write return statement to return explicitly from sub routine.

Sub routine prototype 

Prototypes let you declare subroutines to take arguments just like many of the built-ins, that is, with certain constraints on the number and types of arguments. We call them “prototypes”, but they work more like automatic templates for the calling context than like what C or Java programmers would think of as prototypes. With these templates, Perl will automatically add implicit backslashes, or calls to scalar, or whatever else it takes to get things to show up in a way that matches the template

Example:

sub sum_of_two_squares($$)  {

my ($a, $b) = (shift, shift);

return $a**2 + $b**2;

}

sum_of_two_squares(1,2);      # No run-time error

sum_of_two_squares(1,2,3);  # ERROR

 

Declared as Called as
sub mylink ($$) mylink $old, $new
sub myreverse (@) myreverse $a,$b,$c
sub myjoin ($@) myjoin ":",$a,$b,$c
sub mypop (\@) mypop @array
sub mysplice (\@$$@) mysplice @array,@array,0,@pushme

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s