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

All I need to do is run the sub saveConfig() when a hash is updated. I believe I can do this with tie but I haven't been able to come up with anything yet :)

Replies are listed 'Best First'.
Re: simple tie?
by Beatnik (Parson) on May 27, 2002 at 12:54 UTC
    Try something like :
    Package Tie::Hash::SaveConfig; use strict; use vars qw(@ISA); @ISA = qw(Tie::StdHash); sub TIEHASH { my $class = shift; my %hash; bless \%hash,$class; } sub STORE { my ($self,$key,$value) = @_; $self->SaveConfig($key,$value,$self->{$key}); $self->{$key} = $value; #Redefine value return $value; } sub DELETE { my ($self,$key) = @_; $self->SaveConfig($key,$self->{$key}); return $self->{$key}; } sub SaveConfig { my $self = shift @_; #Do something here } } 1; __END__
    Then tie it as follows...
    use Tie::Hash::SaveConfig; my %hash = (); tie %hash,'Tie::Hash::SaveConfig'; %hash = (Foo=>"Bar");
    Check davorgs perl.com article

    Greetz
    Beatnik
    ... Quidquid perl dictum sit, altum viditur.

      Good answer, Beatnik! Allow me to suggest a simplification to your solution. Use SUPER;) and you don't need the TIEHASH routine.

      Package Tie::Hash::SaveConfig; @ISA = qw(Tie::StdHash); use strict; sub STORE { my $self = shift; SaveConfig(); $self->SUPER::STORE(@_); # or (probably better) here: # SaveConfig(); } sub SaveConfig { # do something ... print "Config saved\n"; } 1;

      Update: Note merlyn's comment below. I put an additional comment into the code. From the original post, though, it's not clear what is actually wanted.

      -- Hofmator

        SaveConfig(); $self->SUPER::STORE(@_);
        I'd swap those two lines: that way the hash is in the new state before the config is saved, unless the point was to save the old config.

        -- Randal L. Schwartz, Perl hacker

        Well I didn't really know what he wanted :) but a ++ ! :)

        Greetz
        Beatnik
        ... Quidquid perl dictum sit, altum viditur.
Re: simple tie?
by virtualsue (Vicar) on May 27, 2002 at 12:08 UTC
    I'm not sure what your question is, so maybe you could read 'perldoc perltie' on your system and then come back and tell us what you need to know. :)