December 2010 Archives

perl5.10, give back our $_

perl5.10 added given keyword. very nice.

However, given("foo") does my $_ = "foo"(lexical $_) implicitly. This means it does not work code using local $_ in given block. like this:

use 5.010;

sub foo(&$) {
    my ($code, $value) = @_;
    local $_ = $value;
    $code->();
}

foo { print $_ } "foo"; # => "foo"

given ('xxx') {
    foo { print $_ } "foo"; # => "xxx"
}

this occurs even List::Util.

use 5.010;
use List::Util qw/first/;

given ('xxx') {
    my $test = first { $_ eq 'xxx' } qw/ bar baz /;
    # $test => bar
}

or Try::Tiny (POD described this point.)

use Try::Tiny;

given ('xxx') {

    try {
        die "error";
    } catch {
        warn $_; # => "xxx"
    }

}

I think we can avoid unnecessary problems by given() make local $_ instead of lexical $_.

What do you think?

of course, It may be there is the purpose of lexical scope that I have not understand.(I dont read all p5p logs.)

and, We can use global $_ this way even inside lexical $_ scope.

given ('xxx') {
    foo { our $_; print $_ } "foo"; # => "foo"
}

or

given ('xxx') {
    foo { print $::_ } "foo"; # => "foo"
}

About Naoki Tomita

user-pic A perl programmer who learn ninjutsu at the weekend.