Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^2: Passing an anonymous block to a method.

by AnomalousMonk (Archbishop)
on Mar 10, 2011 at 21:44 UTC ( [id://892542]=note: print w/replies, xml ) Need Help??


in reply to Re: Passing an anonymous block to a method.
in thread Passing an anonymous block to a method.

I don't understand the comment
    # Prevent $subref from playing with vars
which seems to refer to the lexical variable definition
    my ($self, $key);
which follows it and effectively masks lexicals of the same name defined in a superior scope. Can you please explain further?

Replies are listed 'Best First'.
Re^3: Passing an anonymous block to a method.
by wind (Priest) on Mar 10, 2011 at 22:47 UTC

    AnomalousMonk,

    You are correct. I was mistakenly being overprotective since I was treating an anonymous sub invocation like I was doing an eval. There is no need to worry about scoping of anything except global variables when calling the anon sub. Thank you for making me rethink this.

    Nevertheless, if this was anything more than an example, I would also redesign the method so that it doesn't require an explicit assignment to $_ within the anonymous sub but instead does that assignment for you.

    $self->{ $key } = $subref->();

    I chose to add parameter variables as a way of making the method self-documenting, but I didn't want the anonymous subroutine to have access to the deeper mechanisms of the object. Ideally, the only variable within the anonymous sub will be $_. However, to prevent a user from taking advantage of the lexicals $self and $key, I explicitly hid them.

    If this was anything more than an example, I probably would've localized @_. But then again, I would also redesign the method so that it doesn't require an explicit assignment to $_ within the anonymous sub, but instead does that assignment for you.

    $self->{ $key } = $subref->();

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://892542]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (8)
As of 2024-03-28 12:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found