in reply to Why is my array getting changed?


When you use a for(each) loop in this way it edits the elements of the array in-place:
#!/usr/bin/perl -wl use strict; my @a = (1,2,3); print "@a"; foreach (@a) { $_ *= 2; } print "@a"; foreach my $item (@a) { $item *= 2; } print "@a"; __END__ Prints: 1 2 3 2 4 6 4 8 12

Here is the relevant detail from the "Foreach Loops" section of perlsyn:

If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop.

--
John.

Replies are listed 'Best First'.
Re: Re: Why is my array getting changed?
by Rhose (Priest) on Aug 26, 2002 at 14:49 UTC
    Yep, what jmcnamara said! *Smiles*

    Add the following line to your code and run it...

    #!/usr/bin/perl -w use strict; my @msgtime = (1029435628); my $i; for ( $i = 0; $i <= 2; $i++ ) { foreach my $timealert (@msgtime) { print '[',$timealert,'][',@msgtime,']',"\n"; # <--- Add me! $timealert = ((time - $timealert) / 60); print "$timealert\n"; } }