in reply to HOA with array slice?

I think that the line

my ($idx_color, $idx_fruit) = (0,1);
is a dead giveaway that you should be using an HoH (or even an AoH). By naming your indices you are inadvertently revealing a secret desire to use meaningfully named keys instead. Go for it:
my $hoh = { keyone => { color => 'green', fruit => 'apple' }, keytwo => { color => 'purple', fruit => 'plum' } };
...and here's your slice:
my ( $color, $fruit ) = @{ $hoh->{ keytwo } }{ qw( color fruit ) };
Actually, since you are using such nondescript names for your first keys, maybe an AoH is most suitable:
my $aoh = [ { color => 'green', fruit => 'apple' }, { color => 'purple', fruit => 'plum' }, ]; my ( $color, $fruit ) = @{ $aoh->[ 1 ] }{ qw( color fruit ) };
Granted, come initialization time it gets annoying to re-type the names of the keys so many times. Here's one possible way to avoid that, again featuring slices galore:
my @fields = qw( color fruit ); my $aoh; @{ $aoh->[ @$aoh ] }{ @fields } = @$_ for ( [ qw( green apple ) ], [ qw( purple plum ) ] );

the lowliest monk

Replies are listed 'Best First'.
Re^2: HOA with array slice?
by Transient (Hermit) on May 25, 2005 at 21:34 UTC
    And that, of course, brings you to OOP...which may be better or worse depending on your viewpoint :)
    package Fruit; sub new { my $class = shift; my $self = {}; my $color = shift || ''; my $name = shift || ''; bless $self, $class; $self->color( $color ); $self->name( $name ); return $self; } sub color { my $self = shift; $self->{color} = $_[0] if $_[0]; return $self->{color}; } sub name { my $self = shift; $self->{name} = $_[0] if $_[0]; return $self->{name}; } sub print { my $self = shift; print "I am just a ", $self->color(), " ", $self->name(), "\n"; } 1; package main; my $first_fruits = Fruit->new( 'green', 'apple' ); my $second_fruits = Fruit->new( 'purple', 'plum' ); my @fruit_basket = ( $first_fruits, $second_fruits ); $second_fruits->print();
    This is a fairly basic implementation, you can get as fancy as you'd like.
Re^2: HOA with array slice?
by tphyahoo (Vicar) on May 26, 2005 at 09:57 UTC
    I think tlm is right, I should be using HOH here, so I will be doing a bit of code rewrite.

    One disadvantage of HOH that occurs to me right away though, is if I mistype a key when setting a value in the hash, I don't get any type of error message. I often have autovivification errors that arise in this kind of way.

    Is there any way to program defensively against this kind of error? One thing that occurs to me is I could just use the "functions as constants" thing that ikegami mentions earlier. Anyone else have other defense programming suggestions for dealing with this and autovivification with HOH?

      Several of the replies to this node address the issue you bring up.

      the lowliest monk