Reading and Writing Hash Records to Text Files
Problem
You want to read or write hash records to text files.
Solution
Use a simple file format with one field per line:
FieldName: Value
and separate records with blank lines.
Discussion
If you have an array of records that you’d like to store and retrieve from a text file, you can use a simple format based on mail headers. The format’s simplicity requires that the keys have neither colons nor newlines, and the values not have newlines.
This code writes them out:
foreach $record (@Array_of_Records) {
for $key (sort keys %$record) {
print "$key: $record->{$key}\n";
}
print "\n";
}Reading them in is easy, too.
$/ = ""; # paragraph read mode
while (<>) {
my @fields = split /^([^:]+):\s*/m;
shift @fields; # for leading null field
push(@Array_of_Records, { map /(.*)/, @fields });
}The split acts upon $_, its
default second argument, which contains a full paragraph. The pattern
looks for start of line (not just start of record, thanks to the
/m) followed by one or more non-colons, followed
by a colon and optional white space. When
split’s pattern contains parentheses, these
are returned along with the values. The return values placed in
@fields are in key-value order, with a leading
null field we shift off. The braces in the call to
push produces a reference to a new anonymous hash,
which we copy @fields into. Since that array was
stored in order of the needed key-value pairing, this makes for
well-ordered hash contents.
All you’re doing is reading ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access