Subroutines in PERL - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Subroutines in PERL

Share This

If a set of statements are to be executed many times according to the requirements, the statements are enclosed in a function or subroutine.

In Perl the words, subroutine, method and function, are used interchangeably.

Subroutine Definition and Call

A subroutine is called by it's name as subroutine_name(list of arguments); In old version of perl, subroutine is called as &subroutine_name( list of arguments );

Perl compiles programs before executing it, hence, location of subroutine definition does not matter. Let's have a look into the following example.

#!/usr/bin/perl sub Hello { print "Hello, World!\n"; } Hello();

Passing Arguments to a Subroutine

Various arguments can be passed to a subroutine. These arguments are acessed inside the function like an array using @_ .

Let's try the following example, which takes a list of numbers and then prints their average


#!/usr/bin/perl sub Average { $n = scalar(@_); $sum = 0; foreach $itm (@_) { $sum += $itm; } $avg = $sum / $n; print "Average: $avg\n"; } Average(10, 20, 30);

Passing Lists to Subroutines

@_ can be used to pass lists to a subroutine. But extraction of the individual elements are difficult. Let's try the following program.


#!/usr/bin/perl sub PrintList { my @list = @_; print "The list is @list\n"; } $a = 10; @b = (1, 2, 3, 4); PrintList($a, @b);

Passing Hashes to Subroutines

A hash is automatically translated into a list of key/value pairs when it is passed as argument. Let's try the following example.


#!/usr/bin/perl sub PrintHash { my (%hash) = @_; foreach my $key ( keys %hash ) { my $val = $hash{$key}; print "$key : $val\n"; } } %hash = ('name' => 'John', 'age' => 22); PrintHash(%hash);

Returning Value from a Subroutine

You can return a value from subroutine like you do in any other programming language. If a value is not returned from a subroutine then subroutine automatically returns value we have updated in it.

Similar to array and hash passing in a subroutine, if they are returned from the subroutine their separate identities are lost.

Let's try the following example.


#!/usr/bin/perl sub Average { $n = scalar(@_); $sum = 0; foreach $item (@_) { $sum += $item; } $average = $sum / $n; return $average; } $num = Average(10, 20, 30); print "Average : $num\n";

Private Variables in a Subroutine

By default, all variables in Perl are global variables, which can be accessed from anywhere in the program. If a private variable (lexical variables) is needed, it can be created using my operator.

The block where a private variable is declared, the block becomes it's scope. Such as the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements.

The scope of a variable is shown in the following sample code.


sub somefunc { my $variable; my ($another, @an_array, %a_hash); }

Let's check the following example.


#!/usr/bin/perl $string = "Hello!"; sub Print1 { my $string; $string = "Hi!"; print "Inside $string\n"; } Print1(); print "Outside $string\n";

Temporary Values via local()

In case of local, the current value of a variable must be visible to called subroutines. This is known as dynamic scoping.

If more than one variable or expression is given to local, they must be placed in parentheses.

Let's check the following example.


#!/usr/bin/perl $string = "Hello, World!"; sub Print1 { local $string; $string = "Hello, Perl!"; Print2(); print "Inside Print1 $string\n"; } sub Print2 { print "Inside Print2 $string\n"; } Print1(); print "Outside the function $string\n";

State Variables via state()

These are private variables but they maintain their state, upon multiple calls of the subroutines.

Let's check the following example.


#!/usr/bin/perl use feature 'state'; sub PrintTest { state $count = 0; print "Value is $count\n"; $count++; } for (1..5) { PrintTest(); }

Subroutine Call Context

The context of a subroutine or statement is defined as the type of return value that is expected. For example, in my $str = localtime( time ); a string is returned as it is in scalar context. Whereas in ($sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst) = localtime(time); , the values are stored in different variables.




Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.