Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Journal of jjore (6662)

Friday December 29, 2006
12:29 PM

(?{...}) can use lexicals safely

[ #32016 ]

This is clever and I like it. It lets (?{...}) use a lexical safely. I learned it from almut at

sub ... {
    my @lex;
    ... =~ /...(?{ sub { ... @lex }->( ... ) }).../;

If (?{...}) used @lex directly then the single closure embedded in the regexp would have bound once and forever to only one instance of @lex. All calls to this after the first would be using the @lex from back in time and not the current one.

When (?{sub{ }->( )} uses @lex inside the newly created closure it works because the inner closure has to look at runtime to find @lex. Static (?{}) doesn't have it. The function containing both does and it has the current @lex. sub {}->() binds to the proper, current @lex and everyone is happy.

It's only one level of indirection away so I'm surprised to be learning of this just today. I mean, I can explain why this works, it just never occurred to me that it was possible.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.