Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Referencing globals clobbers data

by Joost (Canon)
on Apr 08, 2002 at 15:14 UTC ( [id://157456]=note: print w/replies, xml ) Need Help??


in reply to Tie-ing hashes clobbers data

Your problem is in the last line of the _read() method:
return \%data; 
this returns a reference to the GLOBAL %FileHash::data that is set by the do $file, so you are using the same hash for all FileHash objects.

The quickest way to solve this is to change the offending line with:

return {%data};
which returns a reference to a COPY of %data, leaving %FileHash::data free to be clobbered by a new do $file

anyway, this will still leave your race conditions intact :-)

Joost.

Replies are listed 'Best First'.
Re: Referencing globals clobbers data
by demerphq (Chancellor) on Apr 08, 2002 at 15:23 UTC
    The quickest way to solve this is to change the offending line with:
    return {%data};
    Hmm, so now he makes a copy of a copy of a copy.... I dont think this is the best call. Do away with the glob semantics and this all becomes very straightforward...

    Yves / DeMerphq
    ---
    Writing a good benchmark isnt as easy as it might look.

      That's why it's called the quick fix :-)

      How about...

      package FileHash; use strict; use warnings; use Tie::Hash; use Data::Dumper; our @ISA = ("Tie::Hash"); sub TIEHASH { my ($class, $file) = @_; my $s = bless { FILE => $file, DATA => {}, },$class; $s->_read(); return $s; } sub STORE { $_[0]->{DATA}->{$_[1]} = $_[2] } sub CLEAR { $_[0]->{DATA} = () } sub FETCH { $_[0]->{DATA}->{$_[1]} } sub FIRSTKEY { my $a = scalar keys %{$_[0]}; each %{$_[0]->{DATA}} } sub NEXTKEY { each %{$_[0]->{DATA}} } sub EXISTS { exists $_[0]->{DATA}->{$_[1]} } sub DELETE { delete $_[0]->{DATA}->{$_[1]} } sub DESTROY { $_[0]->_write } # ----- private subs ----- sub _write { # still need to deal with race conditions my $file = $_[0]->{FILE} ; open (FH, "> $file") or die "Can't open $file for FileHash _write: +$!"; print FH Dumper($_[0]->{DATA}); # writes out as $VAR1 = { ..... } close FH or die "Can't close $file for FileHash _write: $!"; } sub _read { # still need to deal with race conditions my $self = shift; return unless -f $self->{FILE}; $self->{DATA} = do $self->{FILE}; } 1;
        Yup. Thats much better....

        ;-)

        Yves / DeMerphq
        ---
        Writing a good benchmark isnt as easy as it might look.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-03-28 14:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found