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

For lexicals, couldn't the check be done at compile-time?

Replies are listed 'Best First'.
Re^6: Changing array by changing $_?
by JavaFan (Canon) on Oct 13, 2008 at 17:02 UTC
    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.
      I knew I phrased it as a question for a reason :D

      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.