CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner:
reading & saving hashes



Jun 25, 2001, 6:18 AM

Post #1 of 2 (503 views)
reading & saving hashes Can't Post

I'm stuck here. Ive puzzled over this for quite a while. I can't seem to work oour the syntax for reading and saving hashes to a textfile. Is there a way? and if so how does it work?

Thanks in advance

Enthusiast / Moderator

Jun 25, 2001, 7:05 AM

Post #2 of 2 (501 views)
Re: reading & saving hashes [In reply to] Can't Post


there are several ways to put hashes into text files.
First, if you know what's inside the hash, you can simply write an entry for each key -> value pair, with key and value separated by a special character. When reading the file, you can use the split function to separate key and value and put them back in a hash.
If you need something fast, you can use Perl's database interface DBI.
If you want a simple, but still quite universal solution, you can try this piece of code which is based upon the Data::Dumper module. It can even cope with hash or array references inside the hash.

#!/bin/perl -w 
use strict;
use Data::Dumper;

my $hashfile = 'hash.txt';
my %hash = (
hello => 'world',
foo => {
bar => 'gnu',
baz => 'gorilla',
test => [42, 8, 15],

SaveHash( $hashfile, \%hash );

my %read = ReadHash( $hashfile );

print Data::Dumper->Dump( [\%hash, \%read], [qw(*hash *read)] );

# Read hash table from text file
# %hash = ReadHash( FILENAME )
sub ReadHash
my $file = shift;
my %hash;
local $/ = undef;

open FILE, $file or die "Cannot open file `$file' for reading: $!\n";
eval <FILE> or die "Invalid file format!\n";
close FILE;

return %hash;

# Save hash table to text file
sub SaveHash
my($file, $hashref) = @_;

open FILE, ">$file" or die "Cannot open file `$file' for writing: $!\n";
print FILE Data::Dumper->Dump( [$hashref], ['*hash'] );
close FILE;

This can still be improved in several ways (e.g. it doesn't need to die all the way...), but I wanted to keep it simple here.
Hope this helps,

-- Marcus


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives