Perl – foreach the $var (@list) — $var is a reference

foreachperlperlsyn

So, I never knew this and I want to get some clarifcation on it. I know if you do

foreach (@list){

if you change $_ in that loop it will affect the actual data. But, I did not know that if you did

foreach my $var1 (@list){

If you changed $var1 in the loop it would change the actual data. :-/ So, is there a way to loop over @list but keep the variable a read-only copy, or a copy that if changed will not change the value in @list?

Best Answer

$var is aliased to each item in turn.

See http://perldoc.perl.org/perlsyn.html#Foreach-Loops

If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.