Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Local for lexicals

by JavaFan (Canon)
on Aug 10, 2009 at 15:27 UTC ( [id://787355]=note: print w/replies, xml ) Need Help??


in reply to Local for lexicals

No, that's the point of lexicals. If you want dynamic scoping, you don't want lexical scoping. So, don't use a lexical, use a package variable.

Of course, if you use XS, or Devel::Declare, anything is possible, but there's no pure Perl solution.

Replies are listed 'Best First'.
Re^2: Local for lexicals
by JadeNB (Chaplain) on Aug 10, 2009 at 15:31 UTC
    I'm a little confused by the response. It's not the dynamic-scoping-like behaviour that's the problem—
    my $x = 1; my $f = sub { $x }; { $x = 2; print $f->(), "\n"; # => 2 }
    works as desired. (I'm sure that “dynamic scoping” isn't the right term for that, but I didn't know a better.) The real difficulty (for me, anyway) is making a change in an inner scope to a lexical variable in an outer scope in such a way that the change will ‘revert’ outside that scope.
      It's not the dynamic-scoping-like behaviour that's the problem
      Yes, it is:
      The real difficulty (for me, anyway) is making a change in an inner scope to a lexical variable in an outer scope in such a way that the change will ‘revert’ outside that scope.
      That's the dynamic scoping you're after.

      Make $x a package variable, use local, and it will work the way you want. I don't see the point of making $x a lexical if you don't want lexical behaviour.

        I'm sorry; I know that I must be mis-using the terms, but it seems to me that what I'm looking for is not contrary to what one could expect of lexicals. Making a change in an inner scope that is ‘seen’ by an outer scope is what I mean by “dynamic scoping” (although I probably shouldn't), and that is, of course, no problem. Having changes to a variable within a scope undone at the end of that scope is just what scoping means—it seems to me that it has nothing to do with lexical vs. dynamic. Again, aside from magic that can be associated to copying,
        { my $temp = $x; $x = $new; ... $x = $temp; }
        does what I want, obviously without subverting Perl in XS-y ways.

        Is it really the case that setting aside a value to be restored at the end of scope is what is meant by “dynamic scoping”?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-04-25 19:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found