in reply to Saving Hash Values to file
#!/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 |