Friday, June 24, 2011

function call in perl

There are three ways to call function in perl:

sub myfunc {  .  .  .  }
1)&myfunc(1,2,3);                old  style
2)myfunc(1,2,3);                  No ampersand
3) myfunc 1 , 2 , 3;                Works only if myfunc has already been declared.

Sample program:


1)package main;
$aa="hello";
$bb="aaaaa";
&myfunc ($aa,$bb);      #  in this case the subroutine can be defined before or after the function call;
sub myfunc
{
@aa[0]=shift ;
@aa[1]=shift;
print "@aa";
}

output :

hello aaaaa
2)

sub myfunc         # @_ is the default array where all the values are stored
{
@aa[0]=shift ;      # values are shifted
@aa[1]=shift;
print "@aa";
}
package main;
$aa="hello";
$bb="aaaaa";
myfunc($aa,$bb);       #  in this case the subroutine can be defined before or after the function call;

output:

hello  aaaaa
3)In the third case the disadvantage is when u try to call the function without the defining the function in the preceding code it will return error.


package main;
$aa="hello";
$bb="aaaaa";
myfunc $aa,$bb;   # here the myfunc not defined in the preceeding lines.
sub myfunc
{
@aa[0]=shift ;
@aa[1]=shift;
print "@aa";
}

output:

G:\perl_programs>perl function_perl.pl
Can't locate object method "myfunc" via package "hello" (perhaps you forgot to l
oad "hello"?) at function_perl.pl line 5.

It works if used like this:


sub myfunc
{
@aa[0]=shift ;
@aa[1]=shift;
print "@aa";
}
package main;
$aa="hello";
$bb="aaaaa";
&myfunc ($aa,$bb);

output:

hello aaaaa

No comments:

Post a Comment