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

i have a situation where i get hash ref $result from somebody else's module and need to access certain slices. however, the name of the slices are inconsistent because they include a length index: for instance the slice TEST could be named TEST[1] or TEST[3] etc...

i'm trying to access this in the following way: $result->{'TEST[1]'} etc... but, of course this isnt working if it's named TEST[2]. is there a better way to do this, so it will grab TEST no matter what the length index is?

just for your info, the serialized structure (Data::Dumper) of one result set looks like this:

$VAR1 = { 'TEST[2]' => '24', 'RESPMSG[42]' => 'invalid or empty account expir

Janitored by Arunbear - balanced code tag and retitled from 'refernce acess with inconsitent names'

Replies are listed 'Best First'.
Re: Accessing a hash with inconsistent key names
by ikegami (Patriarch) on Oct 25, 2004 at 23:05 UTC

    Here's a good way if you want to fetch multiple values from the hash: (you mentioned slice)

    my $result = { 'TEST[2]' => '24', 'RESPMSG[30]' => 'invalid or empty account expir', }; my %lookup; $lookup{/^(.*)\[\d+\]$/ ? $1 : $_} = $_ foreach (keys(%$result)); print($result->{$lookup{'TEST'}}, $/); # 24 my @slice = @$result{$lookup{'TEST'}, $lookup{'RESPMSG'}}; print(join(', ', @slice), $/); # 24, invalid or empty account expir my @keys = ('TEST', 'RESPMSG'); my %subhash = map { shift(@keys) => $_ } @$result{@lookup{@keys}}; print(join(', ', %subhash), $/); # TEST, 24, RESPMSG, invalid or empty account expir my @keys2 = ($lookup{'TEST'}, $lookup{'RESPMSG'}); my %subhash2 = map { shift(@keys2) => $_ } @$result{@keys2}; print(join(', ', %subhash2), $/); # TEST[2], 24, RESPMSG[30], invalid or empty account expir
Re: Accessing a hash with inconsistent key names
by Zaxo (Archbishop) on Oct 25, 2004 at 23:12 UTC

    Without resort to one of the odd tied hash modules, you can grep for keys matching the base text, my @tests = grep { /^TEST/ } keys %$result; You'll then have to sift those to get the ones you want.

    The use of things that look like indexes on the hash keys suggests that you might want to use a Hash of Arrays instead.

    After Compline,
    Zaxo

Re: Accessing a hash with inconsistent key names
by borisz (Canon) on Oct 25, 2004 at 23:55 UTC
    Or tie your hashref.
    package MyHash; require Tie::Hash; our @ISA = 'Tie::StdHash'; sub TIEHASH { my ( $class, $href ) = @_; bless \( my $x = $href ), $class; } sub FETCH { my ( $self, $key ) = @_; for ( keys %{$$self} ) { next unless /^$key/; return ${$self}->{$_}; } undef; } package main; use Data::Dumper; my $x = { test23 => 12, msg34 => 23 }; tie %h, MyHash, $x; print $h{test}, "\n"; print $h{msg}, "\n"; print $h{m}, "\n";
    output:
    12 23 23
    Boris