L0rdPhi1 has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to tie a large hash (like: $db{userdata}->{username}->{password}) to a file and have it save in Perl code format. This allows me to simply require it to load my hash. It's current saving (rewriting) what's already in the hash but isn't adding new values or modifying old values. I'd like to stay away from modules for the tie part of this too... if it's possible.

I'm currently using the code (sorry for it's length):

# Tying code: tie(%db, wpconfig); ...do stuff with %db :)... untie(%db) if %db; # Tie stuff: package wpconfig; sub TIEHASH { my $class = shift; require 'wpconfig.pl'; # loads data into %db bless \%db, $class; } sub STORE { my ($self, $key, $value) = @_; if (ref $value) { while (($ikey, $ivalue) = each % $value) { if (ref $ivalue) { while (($iikey, $iivalue) = each % $ivalue) { $self->{$key}->{$ikey}->{$iikey} = $iivalue; } } else { $self->{$key}->{$ikey} = $ivalue; } } } else { $self->{$key} = $value; } saveConfig($self); return $value; } sub FETCH { my $self = shift; $self->{$_[1]}; } sub FIRSTKEY { } sub NEXTKEY { } sub EXISTS { } sub DELETE { } sub CLEAR { } sub DESTROY { saveConfig($_[0]); } # saveConfig: This is what actually saves wpconfig.cgi. sub saveConfig { my $self = shift; open GOO, '>wpconfig.pl'; print {GOO} main::genHash(db, \%$self); print GOO "\n1;"; close GOO; } package main; # genHash: What generates the Perl code for my hashes. This works fine +... though if someone wants to explain how to use data dumper to do t +his I'd change it :) sub genHash { my ($name, $hash) = @_; my (@lines, @ilines, @iilines, $entry); $code = "\%$name = (\n"; while (($key, $value) = each %$hash) { $entry = "'$key' => "; if (ref $value) { @ilines = (); $entry .= '{'; while (($ikey, $ivalue) = each %$value) { if (ref $ivalue) { $entry .= "'$ikey' => "; @iilines = (); $entry .= '{'; while (($iikey, $iivalue) = each %$ivalue) { push @iilines, "'$iikey' => q~" . safeTilde($i +ivalue) . '~'; } $entry .= join ",\n", @iilines; $entry .= '}'; } else { push @ilines, "'$ikey' => q~" . safeTilde($ivalue) + . '~'; } } $entry .= join ",\n", @ilines; $entry .= '}'; } else { $entry .= 'q~' . safeTilde($value) . '~'; } push @lines, $entry; } $code .= join ",\n", @lines; return "$code\n);\n"; } # safeTilde: Escapes a ~ (tilde). sub safeTilde { my $code = shift; $code =~ s/\~/\\~/g; return $code; }

Replies are listed 'Best First'.
Re: Tying big hashes
by L0rdPhi1 (Sexton) on May 30, 2002 at 01:19 UTC
    HAHAHA! This is SOO easy I didn't even see it untill just now :) All you have to do is:
    use subs 'exit'; sub exit { saveConfig(); CORE::exit(); }
    No tie required... there goes two and 1/2 days of trying to get tie to work ^_^
      Why not
      END { saveConfig() }
      That's even smaller (and more idomatic) :-)
      -- Joost downtime n. The period during which a system is error-free and immune from user input.