http://www.perlmonks.org?node_id=911167


in reply to Re: simple anonymous subroutine and variable interpolation timing question
in thread simple anonymous subroutine and variable interpolation timing question

I was considering the closure with a local variable, but I was wondering if there was some sneaky way the experts did it. I don't like the looks of the eval method, so I think I'll stick with the first.

Thanks as always Ikegami!

  • Comment on Re^2: simple anonymous subroutine and variable interpolation timing question

Replies are listed 'Best First'.
Re^3: simple anonymous subroutine and variable interpolation timing question
by ikegami (Patriarch) on Jun 23, 2011 at 21:24 UTC

    You don't have to create a separate sub. Alternatives:

    my $sub = sub { my ($str) = @_; sub { $str } }->($str);
    my $sub = sub { my $str = $str; sub { $str } }->();
    my $sub = do { my $str = $str; sub { $str } };
    my $str_copy = $str; my $sub = sub { $str_copy };

    In practice, it's usually a non-issue since you either have a variable that doesn't change to begin with

    for my $str (...) { ... sub { ... $str ... } ... }
    or you want to factor out the code to a sub anyway.
    sub make_list_iterator { my @list = @_; return sub { return @list ? shift(@list) : (); }; } my $iter = make_list_iterator(@list);
Re^3: simple anonymous subroutine and variable interpolation timing question
by tj_thompson (Monk) on Jun 23, 2011 at 21:27 UTC
    errr, meant lexical variable, not local.