René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

foreach [Perl]

The elements in a forach loop are actually aliases:
use warnings;
use strict;

my @array = ('a' .. 'f');

foreach my $element (@array) {
  $element = uc($element);
}

print join "\n", @array;
A
B
C
D
E
F
After the «element» is copied, it is no longer an alias:
use warnings;
use strict;

my @array = ('a' .. 'f');

my $previous_element;
foreach my $element (@array) {
  $previous_element = uc($previous_element) if defined $previous_element;

  $previous_element = $element;
}

print join "\n", @array;
a
b
c
d
e
f
However, it's possible to create a reference to the «element»:
use warnings;
use strict;

my @array = ('a' .. 'f');

my $previous_element;
foreach my $element (@array) {
  $$previous_element = $$previous_element x 2 if defined $previous_element;

  $previous_element = \$element;
}

print join "\n", @array;
aa
bb
cc
dd
ee
f