WINSEM2015-16 CP0067 21-Jan-2016 RM01 Perl Functions
WINSEM2015-16 CP0067 21-Jan-2016 RM01 Perl Functions
C. Prayline Rajabai
Assistant Professor
SENSE
VIT University
INTRODUCTION
A Perl subroutine or function is a group of statements that
together perform a task.
2
DEFINING AND CALLING A SUBROUTINE
Subroutines can be defined using the sub command
Syntax:
sub sub_name {
# Body of the subroutine
#...
}
Syntax:
&sub_name;
&gcd($val1,$val2); # passing two parameters
3
HELLO WORLD EXAMPLE USING SUBROUTINE
Two steps
# Function definition
sub Hello{
print "Hello, World!\n";
}
# Function call
Hello();
4
PASSING ARGUMENTS TO A SUBROUTINE
Various arguments can be passed to a subroutine .
5
RETURN STATEMENT
Use of return statement in a subroutine is optional.
You can return arrays and hashes from the subroutine like
any scalar.
6
RETURN STATEMENT EXAMPLE
sub Average{ # get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
foreach $item (@_){
$sum += $item;
}
$average = $sum / $n;
return $average;
}
# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers : $num\n;
7
Output : Average for the given numbers : 20
PASSING LIST TO SUBROUTINES
Example:
# Function definition
sub PrintList{
my @list = @_;
print "Given list is @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);
8
Output : Given list is 10 1 2 3 4
PASSING HASHES TO SUBROUTINES
When you supply a hash to a subroutine or operator that accepts
a list, then the list is automatically translated into a list of
key/value pairs.
sub PrintHash{
my (%hash) = @_;
foreach my $key ( keys %hash ){
my $value = $hash{$key};
print "$key : $value\n";
}} Output: name : Tom
%hash = ('name' => 'Tom', 'age' => 19); age : 19
Example :
$a = 3.14159;
{ Output :
my $a = 3; In block, $a = 3
print "In block, \$a = $a\n"; In block, $::a = 3.14159
print "In block, \$::a = $::a\n"; Outside block, $a = 3.14159
} Outside block, $::a = 3.14159
print "Outside block, \$a = $a\n";
print "Outside block, \$::a = $::a\n";
12
TEMPORARY VALUES VIA LOCAL
Example :
# Global variable
$string = "Hello, World!";
sub PrintHello{
# Private variable for PrintHello function
local $string;
$string = "Hello, Perl!";
PrintMe();
print "Inside the function PrintHello $string\n";}
sub PrintMe{
print "Inside the function PrintMe $string\n";}
# Function call
PrintHello(); 13
Output :
14
EXERCISE
Write two subroutines. Both use a variable
defined in the body of the program. The first
sub multiplies the variable by ten, while the
second sub divides the number by two. Prompt
the user for the number, and then call both subs
and display the results from the Perl script (not
the subs).
Write a subroutine that expects three numbers
passed as arguments, and multiply the three
together, returning the result from the
subroutine. Call the subroutines from inside a
Perl script that asks the user for all three
numbers. Use names for each argument inside
the subroutine itself. 15