Previous
While 
Next
File Operations 
Beginner's Tutorial for CGI using Perl Language
Functions or Subroutines

Functions or Subroutines

There is one thing that confuses a beginner in perl that concerns functions(or subroutine as they are called in perl) - arguments are passed in a invisible fashion. See the below example to see what I mean.

C++ Functions
int plus(int a, int b)
 {
 int ans=a+b;
 return ans;
 }

One can easily see(or one who knows C++ can easily see) that int a and int b are the arguments. Now lets see the perl function.

Perl Subroutine
sub plus {
...
}

No Arguments! Does that mean that perl can't pass arguments? No, it doesn't. The arguments of perl are stored in an array '@_'. Now you will be asking what is '@_'. This is a predefined variable in perl. These things have special meaning to perl. For example, $_ will be used to store the arguments and default input. $! will be used for error codes. There are many more predefined variables in perl. As a matter of fact, most of the punctuation has special meaning for perl. In this case, @_ stores the arguments passed to the subroutine.

Now lets see the full example...

sub plus {
	my ($a,$b) = @_;
	my $ans = $a + $b;
	return $ans;
}

Notice the line my ($a,$b) = @_; ? This will put the two items of the @_ array into two variables($a and $b) with a local scope. Another way of doing the same is

my $a = @_[0];
my $b = @_[1];

But this way is considered by many to be ugly and "unperlish". The first method is considered by the same group to be elegant and more "perlish".

Calling subroutines are the same as in most other languages...
$answer = plus(4,5);
In this case 4 and 5 will be passed as arguments into the function 'plus' and the answer(9) will be returned and stored in the variable $answer.

The full program will look like this...

#Plus function
sub plus {
	my ($a,$b) = @_;
	my $ans = $a + $b;
	return $ans;
}

my $answer = plus(4,5);
print "The sum of 4 and 5 is $answer.\n";
Previous
While 
Next
File Operations 
Subscribe to Feed