in reply to Re: Odd hash problem
in thread Odd hash problem

Thanks to everyone. One more question, if I may. I know you can load an array directly from a file (@array = <FILE>), is there an easy way to load a hash from a file?

Replies are listed 'Best First'.
Re^3: Odd hash problem
by imp (Priest) on Feb 23, 2007 at 16:05 UTC
    That depends on how the hash was stored.

    You could use Storable to freeze/thaw the hash like this:

    use strict; use warnings; use Storable qw(freeze thaw); use Data::Dumper; my %orig = ( 1 => 2, a => 'b'); my $frozen = freeze(\%orig); print "Frozen: $frozen\n"; my $restored = thaw($frozen); print "Thawed: ", Dumper $restored;
    Or you could be lazy (and insecure) and use Data::Dumper and eval like this:
    use strict; use warnings; use Data::Dumper; $Data::Dumper::Purity = 1; $Data::Dumper::Terse = 1; my %orig = ( 1 => 2, a => 'b'); my $frozen = Dumper(\%orig); print "Frozen: $frozen\n"; my $restored = eval $frozen; print "Thawed: ", Dumper $restored; print "Error: $@\n";
Re^3: Odd hash problem
by johngg (Canon) on Feb 23, 2007 at 20:41 UTC
    I wonder if you meant something different from the answers Fletch and imp gave you. Did you perhaps mean, "How can I populate a hash directly from a file of data like that in my OP?" Something like %hash = {some magic here} <FILE>; rather than while(<FILE>){ # do something # $hash{$key} = $value;}. If that was your question the answer is yes and the magic used would be the map function.

    use strict; use warnings; use Data::Dumper; my %zipDB = map { $_->[0], join q{|}, @{$_}[1 .. 3] } map { chomp; [ unpack q{A5 A2 A3 A*}, $_ ] } <DATA>; print Data::Dumper->Dumpxs([\%zipDB], [qw{*zipDB}]); __END__ 00601PR787ADJUNTAS 00602PR787AGUADA 00603PR787AGUADILLA 00604PR787AGUADILLA 00605PR787AGUADILLA 00606PR787MARICAO 00610PR787ANASCO 00611PR787ANGELES 00612PR787ARECIBO 00613PR787ARECIBO

    The output is

    If I have guessed wrong and this isn't what you meant then I hope the post was of interest anyway :)

    Cheers,

    JohnGG

Re^3: Odd hash problem
by Fletch (Bishop) on Feb 23, 2007 at 15:57 UTC

    Store it as Perl code and use do, or use a serialization format such as YAML (and read it in with YAML::Syck).