Friday, July 19, 2013

Perl : Foreach loop variable is an alias



 In Perl, when an array is traversed using the foreach loop, the variable holding the element of the array during the iteration is actually an alias to the actual element itself. Due to this, any change done to this variable automatically updates the array itself.
   Let us see some examples where every element of an array has to be added by 10:

1. Array elements get updated when updating $_:
#!/usr/bin/perl
use warnings ;
use strict ;
$\="\n";

my @arr=(5..8);
print "@arr";
foreach (@arr){
        $_+=10;
}
print "@arr";
 This snippet when run outputs:
5 6 7 8
15 16 17 18
  As seen above, just by updating the $_, the array elements get updated automatically.

2. Array elements get updated even when using the holding variable:
#!/usr/bin/perl
use warnings ;
use strict ;
$\="\n";

my @arr=(5..8);
print "@arr";
foreach my $x (@arr){
        $x+=10;
}
print "@arr";
   Instead of using the special variable $_, this example uses a lexical variable $x to hold the values in iteration.
The above  snippet outputs:
5 6 7 8
15 16 17 18

3. List of scalar values also gets updated:
#!/usr/bin/perl
use warnings ;
use strict ;
$\="\n";

my ($x,$y,$z)=(20,30,40);

foreach my $a ($x,$y,$z){
        $a+=10;
}
print "$x $y $z";
The sample snippet outputs:
20 30 40
30 40 50
  Even when a set of scalars is given, they too get udpated the same way. The holding variable $a is just an alias to these scalar variables.
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment