in reply to hashes with arrays

Ok, I think I got it.. thanks :-)
$ref->{car}->{Honda}->[0]="Civic"; $ref->{car}->{Honda}->[1]="Accord"; $ref->{car}->{Toyota}->[0]="Camry"; $ref->{car}->{Toyota}->[1]="Tundra"; $ref->{car}->{Toyota}->[2]="Corolla";

Replies are listed 'Best First'.
Re^2: hashes with arrays
by GrandFather (Saint) on Nov 07, 2007 at 00:50 UTC

    Several things there that can be improved on. ;)

    The first is that $ref is a hash reference. More likely you simply want a hash:

    my %ref;

    Perl allows some syntactic sugar that removes all those -> so you can write:

    $ref{car}{Toyota}[2]="Corolla";

    However if you want to initialize a hash then you can:

    my %ref = ( car => { Honda => [qw(Civic Accord)], Toyota => [qw(Camry Tundra Corolla)], } );

    taking advantage of qw so that the car names don't require quoting.


    Perl is environmentally friendly - it saves trees
Re^2: hashes with arrays
by ikegami (Patriarch) on Nov 07, 2007 at 00:53 UTC

    You seem to have an extra level, a hash with a single key.

    $ref->{Honda}->[0]="Civic"; $ref->{Honda}->[1]="Accord"; $ref->{Toyota}->[0]="Camry"; $ref->{Toyota}->[1]="Tundra"; $ref->{Toyota}->[2]="Corolla";

    By the way, the arrow between indexes can be omitted.

    $ref->{Honda}[0]="Civic"; $ref->{Honda}[1]="Accord"; $ref->{Toyota}[0]="Camry"; $ref->{Toyota}[1]="Tundra"; $ref->{Toyota}[2]="Corolla";

    It seems odd to refer to array indexes using a constant.

    $ref->{Honda} = [ qw( Civic Accord ) ]; $ref->{Toyota} = [ qw( Camry Tundra Corolla ) ];

    Or if you were in a loop,

    push @{$ref->{Honda}}, 'Civic'; push @{$ref->{Honda}}, 'Accord'; push @{$ref->{Toyota}}, 'Camry'; push @{$ref->{Toyota}}, 'Tundra'; push @{$ref->{Toyota}}, 'Corolla';