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"; }

In reply to Re: Saving Hash Values to file by jbert
in thread Saving Hash Values to file by Jaspersan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.