The thousand and one reasons to love Perl: [21] The Aliasing Foreach Loop
Like many other languages, Perl has a foreach loop
to iterate over lists of things:
foreach ( @my_list ) {
# do something with each element, available as $_
}
# optionally give the current element a name
foreach my $x (@my_list){
# do something with each element, available as $x
}
The interesting part here is that you access list elements not through a regular variable, but through an alias for the value in the original list, which means that you can change the element in the list:
my @my_list = qw[ ax bx ];
foreach ( @my_list ) {
# change x to y in each element
s/x/y/g;
}
print @my_list;
# prints "ayby"
If you wanted to do that in Java, for example,
you'd have to give up on the foreach loop
and go back to explicit (and verbose) iterators:
for (String s : strings){
// does NOT update the original collection
s = s.replace('x', 'y');
}
// you have to do something like
ListIterator<String> it = strings.listIterator();
while( it.hasNext()){
it.set(it.next().replace('x', 'y'));
}





