in reply to Saving Hash Values to file

If you want to save the hash values only, you need to define a mapping between the order of the values in the file and the keys. If your needs are any more complex than this (and they might get so in the future) you might want to consider using the modules people have mentioned (e.g. Data::Dumper and Storable).
Some people would do this with code only. You can have 'serialise()' and 'deserialise()' functions which contain the order embedded as a sequence of print or assignment statements.
I would also have two functions, but store the order in a shared array (This serves two purposes... "Data is data, not code" and "once and once only"). I would probably also do this in an object, but for the purposes here, I won't:
#!/usr/local/bin/perl -w use strict; my @hash_order = qw( sent recv masters errors ); my $hash_sep = ","; # Return ordered hash values, in one line. Hash passed in by reference sub join_my_hash { my $hr = shift; # The 'map' is just making sure that undefined values # are handled the same as "". return join( $hash_sep, map { defined $_ ? $_ : "" } @$hr{@hash_order} ); } # Return hash (or ref to hash in scalar context) sub split_my_hash { my $line = shift; my %hash; # We don't have a check for too few seperators # We should probably map undefined values here too. @hash{@hash_order} = split( $hash_sep, $line ); return wantarray() ? %hash : \%hash; } # Test it out. my %h = ( sent => 1, recv => 2, masters => 0, errors => 10 , ); # A join my $line = join_my_hash( \%h ); print "join_my_hash: $line\n"; # And split back to a different array my %hn = split_my_hash( $line ); foreach my $k ( keys %hn ) { print "$k: $hn{$k}\n"; }

Replies are listed 'Best First'.
Re: Re: Saving Hash Values to file
by Jaspersan (Beadle) on May 07, 2002 at 12:14 UTC
    Thanks for all the help monks. I'll look into those modules too. :)
    ^jasper <jasper@wintermarket.org>