News for hackers. Stuff that matters.
Re:Perl: When DWIM Doesn't by prakashk on Tuesday January 31, 2012 @01:39PM (#3534554)
This is not much different than mutating a global variable inside a function.

I would write your code as:

    foo($_) foreach @bar;

    sub foo {
        my $var = shift;
        $var =~ s/foo/bar/;
        print $var;
    }
You can also fix this is to localize $_ inside the function, if you don't want to pass $_ as a parameter.

    foo foreach @bar;

    sub foo {
        my $var = $_;
        $var =~ s/foo/bar/;
        print $var;
    }
You can even use $_ instead of $var (although it looks a little weird assigning $_ to itself):

    foo foreach @bar;

    sub foo {
        my $_ = $_;
        s/foo/bar/;
        print;
    }

There are no comments on this comment yet.