haukex has asked for the wisdom of the Perl Monks concerning the following question:
Hi all,
So there's this strange thing you can do:
our %h; my $x = do { local %h=(a=>'3'); \%h }; my $y = do { local %h=(b=>'5'); \%h }; dd \%h; # {} dd $x; # { a => 3 } dd $y; # { b => 5 }
While I wouldn't actually do this, I couldn't seem to find any documentation of it, and I'm wondering if it's "safe" to do, or it is some kind of dark magic that should be avoided. (Also I've only tested it on 5.18 and 5.26 so far.)
The second part of my question is that the Symbol module's gensym claims to return a reference to an "anonymous" glob. But it turns out they're not actually anonymous:
use Symbol qw/gensym/; my $foo = gensym; *$foo->{bar} = 'quz'; dd \%Symbol::GEN0; # { bar => "quz" }
So I'm wondering why Symbol::gensym isn't just implemented like this, which I got from BrowserUk's post here? It seems to me that, while the globrefs are still associated with a name, they really do seem to be more "anonymous".
sub gensym { \do{ local *ANONGLOB; *ANONGLOB } }
In the thread I linked to, tye mentions that unique names make debugging a bit easier, but I am wondering if there are any other technical downsides to the above?
Thanks,
-- Hauke D
Update 2017-09-05: So Tie::StdHandle has been doing something like this for about 18 years now: my $fh = \do { local *HANDLE };
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Referencing localized variables, and typeglobs
by AnomalousMonk (Archbishop) on Aug 30, 2017 at 23:27 UTC | |
Re: Referencing localized variables, and typeglobs
by Laurent_R (Canon) on Aug 30, 2017 at 20:13 UTC | |
by haukex (Archbishop) on Aug 30, 2017 at 21:07 UTC | |
by Laurent_R (Canon) on Aug 30, 2017 at 21:38 UTC | |
Re: Referencing localized variables, and typeglobs
by kcott (Archbishop) on Aug 31, 2017 at 05:22 UTC | |
Re: Referencing localized variables, and typeglobs
by BrowserUk (Patriarch) on Aug 30, 2017 at 20:29 UTC | |
by haukex (Archbishop) on Aug 30, 2017 at 21:13 UTC | |
Re: Referencing localized variables, and typeglobs
by haukex (Archbishop) on Aug 31, 2017 at 16:57 UTC |