in reply to Re: Unshift and push inside of map operation.
in thread Unshift and push inside of map operation.

map and also foreach don't well work with changing arrays.

That's an odd thing to say about map since map has nothing to do with arrays. map iterates over a list, and it has no problem working with a list built from an array. Changes to the array are ignored because map doesn't iterate over arrays.

foreach has optimizations which can causes unreliabilities when modifying the array over which it iterates, but map doesn't. It's very reliable in its behaviour.

Replies are listed 'Best First'.
Re^3: Unshift and push inside of map operation. (optimizations)
by tye (Sage) on Sep 23, 2008 at 04:57 UTC
    foreach doesn't, but that's an odd thing to say about map since map has nothing to do with arrays. map iterates over a list, and it has no problem working with a list built from an array.

    You are assuming a lack of optimizations and levels of optimization are very much subject to change. I strongly suspect that there are older versions of Perl that didn't optimize foreach over a single array. I suspect that there will be future versions of Perl that can optimize map/grep over a single array. Indeed, I'm not convinced that there aren't already versions of Perl that can optimize such (nor have I seen evidence that there are such, but I prefer to not assume things about levels of optimization exactly because they are so subject to change).

    It is merely an optimization that makes foreach treat a single array differently than some other list. There is little to stop map or grep from acquiring a similar optimization. So I find it "odd" for you to make such a stark distinction between them.

    - tye        

Re^3: Unshift and push inside of map operation.
by jethro (Monsignor) on Sep 23, 2008 at 04:23 UTC
    I meant "doesn't work well" in the sense LNEDAD wanted to use it.

      Whatever you meant doesn't apply to both foreach and map.

      foreach doesn't work well with changing arrays.
      map works well with changing arrays.

      foreach can do what the OP wants, but not well.
      map doesn't do what the OP wants at all.

        Um no. map doesn't like changing arrays either:
        #!/usr/bin/perl use Devel::Peek; @a = (1,2); @b = map { pop @a; Dump $_; } @a; $ perl5100 /tmp/p SV = IV(0x9cd41d4) at 0x9cd41d8 REFCNT = 1 FLAGS = (IOK,pIOK) IV = 1 SV = UNKNOWN(0xff) (0x9cd40b8) at 0x9cd4308 REFCNT = 0 FLAGS = ()

        Dave.