Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^3: use 'local' modifier to hashref element

by rovf (Priest)
on Jun 05, 2013 at 15:44 UTC ( [id://1037254]=note: print w/replies, xml ) Need Help??


in reply to Re^2: use 'local' modifier to hashref element
in thread use 'local' modifier to hashref element

I'm mostly interesting in localization of variables with lixical scope.
As you already point out, local acts on the symbol table of the respective package, i.e. on global variables. In your case, I don't see a way how you can have a single hash element automatically restored at the end of the block.

If this feature is really important to you, did you consider a package global variable declared with "our" (i.e. a lexically scoped global variable) as an alternative? However, I personally would restore the hash entries manually at the end of the block.

-- 
Ronald Fischer <ynnor@mm.st>

Replies are listed 'Best First'.
Re^4: use 'local' modifier to hashref element
by kennethk (Abbot) on Jun 05, 2013 at 15:54 UTC
    You may want to reconsider what you've said here.
    use strict; use warnings; use Data::Dumper; my %hash = (1 => 2, 3 => 4); BLOCK: { local $hash{1} = 5; print Dumper \%hash; } print Dumper \%hash;
    What you've said is true for localizing lexical scalars; however localizing values in lexical arrays and hashes is no problem. See When to Still Use local(), item #3. Sorry if I've misread your intent.

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Re^4: use 'local' modifier to hashref element
by Anonymous Monk on Jun 05, 2013 at 21:00 UTC
    Test it. It works. It is more reliable than manually restoring code because you don't have redundant code to mess up on, and because you don't have to worry about exceptions skipping that code. I've been using the trick since Perl 5.005. The ONLY type of scalar that you can't use local on is one defined with my. And that was rejected not because it was hard - it is easy - but because Larry Wall thought that it would confuse people to allow that.

      I tried - and to surprise, indeed, it worked!!!

      So once more I learned something new....
      -- 
      Ronald Fischer <ynnor@mm.st>

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-04-20 01:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found