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

My system uses arrayrefs of arrayrefs containing what are in effect key-value pairs, e.g.:

$pairs = [ ['fish','fry'], ['clam','bake'], ['wiener','roast'], ];

It uses this data structure rather than a hash because it works better with the algorithms used in some places. I would like to access the data, however, as if it were a hashref, with similar syntax.

Here is a construct I came up with:

my $party = {map{@$_}@$pairs}->{'fish'};

The value 'fry' will be assigned to $party.

The one caution is that if there is more than one element in $pairs with the key 'fish' (there should not be, but...), there may be problems. I believe the last element in the array with this key will be used.

Does anyone have thoughts on this? Is there a better way to do what I am describing?

Replies are listed 'Best First'.
Re: Pushing arrays into hashes
by Roy Johnson (Monsignor) on Jun 22, 2007 at 18:12 UTC
    I'd be inclined to use grep or perhaps List::Util first.
    my $party = (grep $_->[0] eq 'fish', @$pairs)[0]->[1];
    use List::Util 'first'; my $party = (first {$_->[0] eq 'fish'} @$pairs)->[1];
    though it's more a case of just being different ways to do it, rather than better ways.

    What probably would be better is to make a function "as_hash" that would do the conversion to a hashref (the map), so that your code would be more self-documenting.

    sub as_hash { my $aref = shift; return { map @$_, @$aref }; }

    Caution: Contents may have been coded under pressure.
      Thank you! I will try this.
Re: Pushing arrays into hashes
by guinex (Sexton) on Jun 22, 2007 at 18:54 UTC
    I would like to access the data, however, as if it were a hashref, with similar syntax.
    Frankly, I don't think this is a worthwhile goal. I expect that whatever you come up with will be more confusing than just defining a helper function to access your data structure. At least for those who have to read your code later.

    -guinex

Re: Pushing arrays into hashes
by Jenda (Abbot) on Jun 23, 2007 at 19:12 UTC

    Maybe it would be better to ask for help with the "algorithms used in some place" and use a hash. It's more efficient to call values() or keys() a few times than it's to build a hash or use grep() or first() whenever you do need to find out the value for a key.

      Thank you! I will dig into this a bit.