in reply to Re: these aren't locals, but they seem to act like it
in thread these aren't locals, but they seem to act like it

you are accessing a global (i.e. package) variable named $flags, not a lexical variable.

I see... I was under the mistaken idea that perl would dereference $$var up the scoping levels till it found a match, and only use global/package names as last resort.

It'd be sure nice to have such a feature. :-/

  • Comment on Re^2: these aren't locals, but they seem to act like it

Replies are listed 'Best First'.
Re^3: these aren't locals, but they seem to act like it
by bart (Canon) on Mar 12, 2007 at 11:43 UTC
    It'd be sure nice to have such a feature. :-/
    Well, I think you can, because eval STRING behaves pretty much this way. So, you can use
    $ref = eval "\\\$$name";
    to get a real reference of the variable you know the name of — a reference, not the value, so you're actually able to change the value. Try it:
    #! perl -w use strict; my $ref; my $name = 'x'; our $x; $x = 'global'; $ref = eval "\\\$$name"; print "\$$name = '$$ref'\n"; { my $x = 'lexical'; $ref = eval "\\\$$name"; print "\$$name = '$$ref'\n"; { my $x = 'nested lexical'; $ref = eval "\\\$$name"; print "\$$name = '$$ref'\n"; } }
    Result:
    $x = 'global' $x = 'lexical' $x = 'nested lexical'

    Caution: You do realize that you're skating on very thin ice, do you? In other words, only use this feature to help you debug what is going on (even though I'm not sure how it could help), do not ever use this in production code to reach for any variable that can be used anywhere in your code.

    But, for debugging purposes, it still won't work to get at variable you don't have normal access to, such as lexicals in a sub that calls your sub. For that purpose, there is PadWalker.

Re^3: these aren't locals, but they seem to act like it
by chromatic (Archbishop) on Mar 11, 2007 at 21:03 UTC

    That would make code difficult to debug (what if you have variable shadowing?), but if you really want some deep hurting, try PadWalker.

Re^3: these aren't locals, but they seem to act like it
by Anonymous Monk on Mar 12, 2007 at 04:17 UTC
    Why it's stupid to `use a variable as a variable name' Part 1 2 3