saintmike has asked for the wisdom of the Perl Monks concerning the following question:

Is there a way to make a hash entry go away after leaving the current dynamic scope? Similar to
sub func { local($foo); $foo = "bar"; }
where $foo goes back to normal after leaving func(), I'd like to have something like
sub func { my($self) = @_; $self->{foo} = "bar"; }
only that $self->{foo} should go back to the original value automatically after func() ends.

Ideas, anyone?

Replies are listed 'Best First'.
Re: local() magic with hash entry?
by diotalevi (Canon) on Jul 07, 2006 at 23:26 UTC
    local $self->{foo} = 'bar';

    Next time read your documentation first.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

      local $self->{foo} = 'bar';
      i have been programming Perl for more than seven years now, but until today i didn't know that you can localize hash elements, if the hash itself is a lexical variable. nice =)

        Not just lexicals:

        our %hash=(0..5); { local $hash{2}=4; print "in: 2 => ", $hash{2}, "\n"; } print "out: 2 => ", $hash{2}, "\n"; __END__ in: 2 => 4 out: 2 => 3

        --
        David Serrano