Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach my $var (@list) -- $var is a reference?

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?

like image 381
Ryan Detzel Avatar asked Jun 18 '09 15:06

Ryan Detzel


People also ask

How foreach loop works in Perl?

A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range.

How do I end a foreach loop in Perl?

The Perl last statement is used inside a loop to exit the loop immediately. The last statement is like the break statement in other languages such as C/C++, Java.


1 Answers

Make a copy of @list in the for statement:

foreach my $var1 (() = @list) {
  # modify $var without modifying @list here
}
like image 91
MkV Avatar answered Oct 10 '22 21:10

MkV