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

I do not agree.

If you need help in this department, write a Perl::Critic rule that checks whether you make a copy as the first line of your map/grep/for/foreach/sub block. Your suggestion would mean slowing down almost any scalar assignment done.

Replies are listed 'Best First'.
Re^5: Changing array by changing $_?
by ikegami (Patriarch) on Oct 13, 2008 at 15:38 UTC
    For lexicals, couldn't the check be done at compile-time?
      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 !

Re^5: Changing array by changing $_?
by gone2015 (Deacon) on Oct 13, 2008 at 16:10 UTC

    OK. I can just about imagine how assignment to an ordinary scalar and assignment via an alias would be the same at run-time -- at run-time it doesn't much matter where the pointer to the SV has come from.

    However, I would have thought that the two must be distinguished at compile time -- something has to take care of the implied dereference -- for no run-time penalty.

    I realise that there are plenty of other traps for the new and the unwary -- but I can still remember the pain of learning about this one !

      I would have thought that the two must be distinguished at compile time

      A lexical var is either always an alias or never an alias, so you can for those. But it's a different story for globals.

      sub func { $_ = "foo"; } func() for my $var; # $_ is an alias func(); # $_ isn't an alias

      Update: Oops, not even for lexicals if you use Data::Alias. But you could say that if alias is being used, you know you're dealing with an alias.