in reply to Re: Problem with -d inside find sub
in thread Problem with -d inside find sub

Found another interesting issue. Run the code below as is. It works fine. Then uncomment the given/when blocks and run it again. When I do that I see the same name printed out over and over instead of the correct file names.
use strict; use warnings; use 5.010; use File::Find qw/find/; my $dir = 'dirname'; my @all; #given ($dir) { #when (-d) { my %options = ( wanted => sub { say; }, no_chdir => 1, ); find \%options, $dir; #} #} local $" = "\n"; say "@all";

Replies are listed 'Best First'.
Re^3: Problem with -d inside find sub
by Anonymous Monk on Apr 27, 2012 at 12:01 UTC
    Two solutions:
    1. Declare the %options outside of the given-when blocks.
    2. say $File::Find::name;
      Weird. I wonder why given/when blocks would handle hash lexicals differently than any other kind of block. Definitely seems like a perl bug.
        The problem is with local and lexical $_
        Example:
        use 5.010; sub my_sub (&) { my $code = shift; local $_ = '1234'; $code->(); } my_sub { say }; given ("test") { when ("test") { my_sub { say }; } }
        Output:
        1234 test
        Why?
        Because my $_ (lexical - from the given/when blocks ($_ = 'test')) has a higher priority (aka is in the block where you are) than the local $_ (local - from the my_sub ($_ = '1234')

        How to fix this?
        use 5.010; sub my_sub (&) { my $code = shift; local $_ = '1234'; $code->(); } my_sub { say }; sub my_sub2 { my_sub { say }; } given ("test") { when ("test") { my_sub2(); } }