in reply to split to hash, problem with random keys

This might work for you... It does break on a badly formatted file, though.
test.txt
Test1|Test2|Test3
Foo1|Foo2|Foo3
Code
use strict;

my @records;
my @keys = qw(FirstKey SecondKey ThirdKey);

sub getkey()
{
    my $ret = shift @keys;
    push @keys, $ret;
    return $ret;
}

open IN, "<test.txt";

while(<IN>)
{
    my %record; 
    map{$record{getkey()}=$_} split(/\|/) ;
    push(@records,\%record);
    
}


foreach my $rec (@records)
{
    my %thing = %{$rec};
    foreach my $key (@keys)
    {
        print "$key: $thing{$key}\n";
    }
}
--
Jason Klueber
ookami@insightbb.com

/(bb)|^b{2}/
--Shakespeare
  • Comment on Re: split to hash, problem with random keys

Replies are listed 'Best First'.
Re: Re: split to hash, problem with random keys
by december (Pilgrim) on Jul 04, 2003 at 13:47 UTC

    I've been trying something like this too, but I didn't get the map working (I tried to use a 'values %hash' loop instead of your 'getkey' function, but there I had the same problem of pseudo-random order). I have to remember the shift rotating trick, though...

    Breakage is not an issue, since I make (lock/edit/...) the files myself and can therefore guarantee their integrity. Or so I hope. ;)