[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Hash of arrays of arrays...aaaargh.



My spies tell me that one "Alex Hooper" wrote:

>I'm trying to build what I thought would be a fairly simple data structure:
>a hash of arrays of arrays. I want to read in a tab delimitted text file a
>bit like this:
>
>cat1	item1	price1	desc1
>cat1	item2	price2	desc2
>cat2	item1	price1	desc1
>cat2	item2	price2	desc2
>...
>
>
>Each line becomes an array of length 4; each array is added to another
>array until the category changes (eg, from 'cat1' to 'cat2'), at which
>point, this array is added to a hash with a key equalling the category name
>(eg, 'cat1').

here's my (untested) guess

$dsR = {};

while(<INPUT>) {
    chomp;
    my @list = split /\t/;
    my $cat = $list[0];
    if(exists($dsR->{$cat})) {
        $dsR->{$cat}[$#{$dsR->{$cat}] = [ @list ];
    } else {
        $dsR->{$cat} = [ [ @list ] ];
    }
}

you'll note that the above code does not enforce your requirement that 
all things in a given category must be grouped together in the input 
file, but adding that would be pretty straight forward. this data 
structure should allow you to access individual elements like this:

    $price = $dsR->{'my cat'}[12][2];

and arrays like this:

    @line = @{$dsR->{'my cat'}[12]};
    @cat = @{$dsR->{'my cat'}};

if you want to get fancy and do references to arrays, try this:

    $lineR = $dsR->{'my cat'}[12];
    $catR = $dsR->{'my cat'};

enjoy.




***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch