in reply to Re^5: Changing array by changing $_?
in thread Changing array by changing $_?

chomp (my $module = shift); require $module or die; for my $foo (@array) { func($foo); }
How are you going to determine at compile time whether $foo gets modified? Because if func changes its $_[0], the elements of @array get modified.

Replies are listed 'Best First'.
Re^7: Changing array by changing $_?
by ikegami (Patriarch) on Oct 13, 2008 at 17:17 UTC
    I knew I phrased it as a question for a reason :D
Re^7: Changing array by changing $_?
by gone2015 (Deacon) on Oct 13, 2008 at 17:42 UTC

    There's a mechanism to cope with:

    func('Hello Sailor') ;
    which might be extended to passing of aliases, under suitable strictness...

    You are right. This particular trap is deeper, darker and altogether more ghastly than I thought !

      Said mechanism is to make the SV readonly.
      >perl -MDevel::Peek -e"Dump('Hello Sailor')" SV = PV(0x228e68) at 0x1831670 REFCNT = 1 FLAGS = (PADBUSY,PADTMP,POK,READONLY,pPOK) ^^^^^^^^ PV = 0x1833f3c "Hello Sailor"\0 CUR = 12 LEN = 16

      Obviously that mechanism won't help you here.

      In fact, a flag alone won't work since you'd need to know how many times a variable has been aliased to know when to remove the flag. (Upd: I'm not sure about the preceding statement. Can't think straight right now. )

      You could add magic to the variable like taint does.

      >perl -T -MDevel::Peek -e"Dump($ARGV[0])" foo SV = PVMG(0x1822dcc) at 0x226ba0 REFCNT = 1 FLAGS = (GMG,SMG,pPOK) IV = 0 NV = 0 PV = 0x182d324 "foo"\0 CUR = 3 LEN = 4 MAGIC = 0x182d33c MG_VIRTUAL = &PL_vtbl_taint MG_TYPE = PERL_MAGIC_taint(t) MG_LEN = 1

      But now you're getting into costly.

        OK, the penny is dropping...

        So the @_ is an array of SV*. To distinguish aliases as arguments requires the pointer, not the target, to be marked -- it's only assignments via the alias that should be trapped. That would add overhead.

        Mind you, the compiler knows when it's assigning to $_[x], and only then does it need to worry about copies of aliases -- I think the propagation of aliases is limited -- so I guess the overhead could be contained... assuming one could figure out a way of passing the information with the pointer. Hmmm. I'm starting to feel queasy.

        Well, nothing's perfect... if the 99% cases (lexically inside the foreach/map/etc) were trapped at compile-time it would be a step in the right direction.