nwkcmk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, The foreach block below overwrite all the elements in @test with A. Can anybody tell me if this is a feature or a bug?
@test = (1,2,3,4); foreach my $_tempvar (@test) { $_tempvar = "A"; } print @test;
Many thanks in advance!!

Replies are listed 'Best First'.
Re: foreach array manipulation
by ikegami (Patriarch) on Jan 26, 2005 at 06:45 UTC

    Feature. for/foreach variables are refences (in the C meaning) instead of copies. If you want to copy, try this:

    @test = (1,2,3,4); foreach (@test) { my $_tempvar = $_; $_tempvar = "A"; } print @test;
Re: foreach array manipulation
by monkfan (Curate) on Jan 26, 2005 at 06:40 UTC
    Hi,

    This is not a bug. You are assigning value "A" for the variable "$_tempvar". So it replace the orginal $_tempvar value which were taken from @test element originally.

    What are you trying to do exactly with $_tempvar?
    Perhaps you can tell us your intention, so we can give suggestions.

    Regards,
    Edward
Re: foreach array manipulation
by Hena (Friar) on Jan 26, 2005 at 06:42 UTC
    I would say this is as it should be. As it allows you to change the values of the array with foreach loop, which is faster than others (for or while).
      As it allows you to change the values of the array with foreach loop, which is faster than others (for or while).
      Huh?!? Maybe I misunderstood the sense of your words, but C<for> and C<foreach> are just synonims. Or were you referring to C-style C<for>'s (C<while>'s in disguise)?!?
        According to the people "who wrote the book on Perl" {grin}, there is indeed a "for" loop (what you would call "C style"), and a "foreach" loop (stolen mostly from C-shell). Even though the keywords of "for" and "foreach" are interchangeable, we call a foreach loop a foreach loop even when it's spelled "f-o-r".

        -- Randal L. Schwartz, Perl hacker
        Be sure to read my standard disclaimer if this is a reply.

        Yup, i do call '($i=0;$i<$j;$i++) {}' a for loop and 'foreach (@list) {}' a foreach loop. I don't use 'for (@list) {}' inorder to avoid confusion like this :).

        But thanks for merlyn for info on what others think.
Re: foreach array manipulation
by nwkcmk (Sexton) on Jan 26, 2005 at 07:01 UTC
    Thanks everybody!! It is clear to me now.
Re: foreach array manipulation
by blazar (Canon) on Jan 26, 2005 at 08:48 UTC
    Feature. Clearly documented too...