11.10. Reading and Writing Hash Records to Text FilesProblemYou want to read or write hash records to text files. SolutionUse a simple file format with one field per line: FieldName: Value and separate records with blank lines. DiscussionIf 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 All you're doing is reading and writing a plain text file, so you can use related recipes for additional components. You could use Recipe 7.11 to ensure that you have clean, concurrent access; Recipe 1.13 to store colons and newlines in keys and values; and Recipe 11.3 store more complex structures. If you are willing to sacrifice the elegance of a plain textfile for a quick, random-access database of records, use a DBM file, as described in Recipe 11.14 . See Also
Copyright © 2001 O'Reilly & Associates. All rights reserved. |
|