http://www.perlmonks.org?node_id=930521


in reply to Array got modified!

  1. Yes it is normal
  2. Yes, all versions.
From `perldoc perlsyn`, in the "Foreach Loops" section:
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.

Replies are listed 'Best First'.
Re^2: Array got modified!
by exilepanda (Friar) on Oct 10, 2011 at 02:54 UTC
    O!! Thx man! This explains a lot. Never notice for yrs.
    So I am gonna change my habit to do this way :
    @arr = qw/Foo Bar Blaz/; foreach ( @arr ) { my $ele = $_; $ele =~ s/^(.)/x$1/; } # or this while ( my $ele = <@arr> ) { $ele =~ s/^(.)/x$1/; } print "@arr"; # still 'Foo Bar Blaz'
    Would you suggest which one is better, or any well suggested practice?

      Could you explain, in your own words, what does the while ( my $ele = <@arr> ) { do?

      Once you do, go check the docs!

      It may seem to do what you seem to want if you are unlucky enough and the @arr doesn't contain anything interesting to the diamond operator, but even then it's horribly inefficient.

      Jenda
      Enoch was right!
      Enjoy the last years of Rome.

        Hmm... my try is to take that array as a file handle to read, like @ARGV;

        I add up this code :

        @x = qw/Foo Bar Blaz/; #@x = qw//; print "Before: @x$/"; while ( my $ele = <@x> ) { next unless $ele; print "$ele becomes "; $ele =~ s/^(.)/x$1/; print $ele . $/; } print "$/After: @x"; __END__ Then I have : Before: Foo Bar Blaz Foo becomes xFoo Bar becomes xBar Blaz becomes xBlaz After: Foo Bar Blaz
        Is this work out properly by accident? This is what I want though...
        My observation is:
        if that's a empty array, it skips fine.
        And, without the diamond quote, it loops forever...

      What is the point in editing $ele, if you then discard it?

        haha.. sorry I mislead something... In general to say, I am not trying to edit the array, I just want to loop through and read the array

        By all means, I have to pick elements out, one by one, change to some expected pattern, then throw it to other subs to do something( which I didn't state in the code ).

        Also, it implies that, I will reuse the created array again, so that I don't want it changed.

      Never mind, I did not read the post properly.