in reply to Referencing localized variables, and typeglobs

G'day haukex,

What you've described here, with respect to local, is pretty much how I've always understood this to work: no dark arts or black magic; effectively, just a simple pushing and popping of a stack.

In a subsequent reply, you referenced "perlsub: Temporary Values via local()" and then wrote: "Without some reassurance from the docs, one might worry that the temporary variables might somehow "go away" when the scope exits ...". The following code tracks %h through a do block (similar to your code); in addition, do contains an anonymous block which creates new temporary values. It also tracks the lexical $r: declared but uninitialised before do; assigned a value within the anonymous block; and shown to retain that value after do.

#!/usr/bin/env perl use strict; use warnings; use Data::Dump; my $r; print "\$r UNDEF\t"; dd $r; our %h = (z => 26); print "%h BEFORE do\t"; dd \%h; my $x = do { print "PRE local\t"; dd \%h; local %h; print "POST local\t"; dd \%h; %h = (a => 1); print "POST assign\t"; dd \%h; print "%h BEFORE anon\t"; dd \%h; { print "PRE local2\t"; dd \%h; local %h; print "POST local2\t"; dd \%h; %h = (b => 2); print "POST assign2\t"; dd \%h; $r = \%h; print "\$r ASSIGNED\t"; dd $r; } print "%h AFTER anon\t"; dd \%h; \%h; }; print "%h AFTER do\t"; dd \%h; print "\$x AFTER do\t"; dd $x; print "\$r FINAL\t"; dd $r;

Output:

$r UNDEF undef %h BEFORE do { z => 26 } PRE local { z => 26 } POST local {} POST assign { a => 1 } %h BEFORE anon { a => 1 } PRE local2 { a => 1 } POST local2 {} POST assign2 { b => 2 } $r ASSIGNED { b => 2 } %h AFTER anon { a => 1 } %h AFTER do { z => 26 } $x AFTER do { a => 1 } $r FINAL { b => 2 }

Hopefully, that's a bit more reassuring. :-)

— Ken