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

I want to do this:

open (FILE,$file); # $file is a |-delimited file my @header = ('h1','h2','h3'); # I already know the headings my %values; # make a hash of hashes to remember the values while (<FILE>) { chomp; my @columns = split /\|/; my $unique = $columns[1]; # h2 is the unique identifier @values{$unique}{@header} = @values; }

... but I get a Can't use subscript on hash slice error. Is there a good way to do this without doing it "manually?" I can think of several ugly ways to do it. I know @values{@header} = @columns; works, so I assume it will work for a more complex hash.

Dave

Replies are listed 'Best First'.
Re: Slice of a hash of hashes
by chipmunk (Parson) on Jan 08, 2001 at 21:41 UTC
    It looks like you're dereferencing things in the wrong order. Try this: @{ $values{$unique} }{@header} = @values; $values{$unique} is a hash reference; $values{$unique}{$header} is a single element from the referenced hash; and @{$values{$unique}}{@header} is a hash slice on the referenced hash.
Re: Slice of a hash of hashes
by davorg (Chancellor) on Jan 08, 2001 at 21:46 UTC

    This seems to do the job:

    #!/usr/bin/perl -w use strict; my @header = ('h1','h2','h3'); # I already know the headings my %values; # make a hash of hashes to remember the values while (<DATA>) { chomp; my @columns = split /\|/; my $unique = $columns[1]; # h2 is the unique identifier @{$values{$unique}}{@header} = @columns; } __END__ val1|one|1 val2|two|2 val3|three|3

    I assume that the @values was a typo and have changed it to @columns.

    --
    <http://www.dave.org.uk>

    "Perl makes the fun jobs fun
    and the boring jobs bearable" - me