Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Why is my array getting changed?

by Limbic~Region (Chancellor)
on Aug 26, 2002 at 14:32 UTC ( [id://192881]=perlquestion: print w/replies, xml ) Need Help??

Limbic~Region has asked for the wisdom of the Perl Monks concerning the following question:

Ok, I have been up for practically 3 days straight and I am sure that I have just over looked something. Here is an overly simplistic example of my problem. I am getting file information and sticking it into an array. I then need to check those times against 3 different types of alerts. The outter for loop goes through 3 times and the inner foreach loop goes through one time. There are never any changes to my @array, and yet the result changes every time through - what the heck am I missing???
#!/usr/bin/perl -w use strict; my @msgtime = (1029435628); my $i; for ( $i = 0; $i <= 2; $i++ ) { foreach my $timealert (@msgtime) { $timealert = ((time - $timealert) / 60); print "$timealert\n"; } }

Replies are listed 'Best First'.
Re: Why is my array getting changed?
by jmcnamara (Monsignor) on Aug 26, 2002 at 14:42 UTC

    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.

      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"; } }
Re: Why is my array getting changed?
by Zaxo (Archbishop) on Aug 26, 2002 at 14:39 UTC

    The time function returns a different time later on.

    Update: Uhhh... also the in-place modification jmcnamara++ spotted :)

    After Compline,
    Zaxo

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://192881]
Approved by Courage
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2024-04-25 08:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found