Friday, December 19, 2014

What is the difference between $_ and @_ variables in Perl?

Both $_ and @_ are global variables.

In a subroutine, the array @_ pass the arguments to the given subroutine
Consider the example below,

sub print
{
foreach my $arg(@_) // @_ contains, abc, xyz, lmn, It collects from call and keeps them during execution
{
print "To Print =>$arg\n";
}
}

print('abc','xyz','lmn');

Output :
To Print =>abc
To Print =>xyz
To Print =>lmn

$_ is used as a variable for the loop

foreach(1..5)
{
  print "$_\n";
}

Output
1
2
3
4
5

Combining both the features

sub print
{
  foreach(@_)
  {
    print "You passed in $_ \n";
  }
}

print('abc','xyz','1','2','true');

No comments:

Post a Comment