in reply to Can I avoid loops getting the single value from a hash without knowing the key?
Here's a not-thoroughly-tested | moderately-well-tested recursive approach for any reference to a hash/array-of-hash/array structure of any depth. Whether this is "nice" is perhaps debatable, but at least it avoids a for-loop.
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $ComponentData = { 'key_A' => { '6.0' => [ { 'FILENAME' => 'filename', 'VERSION' => 'version', ooo => ' +xxx', }, ], }, }; dd $ComponentData; ;; print highest_multi_element($ComponentData)->{FILENAME}; print highest_multi_element($ComponentData)->{ooo}; my $coderef = sub { return { ooo => 'yyy' }; }; print highest_multi_element($coderef)->{ooo}; ;; sub highest_multi_element { my $dataref = shift; ;; if (ref $dataref eq 'HASH') { my ($single, $val, $multi) = %$dataref; die 'empty hash' unless defined $single; return defined $multi ? $dataref : highest_multi_element($val); } elsif (ref $dataref eq 'ARRAY') { my $items = @$dataref; die 'empty array' unless $items; return $items > 1 ? $dataref : highest_multi_element($dataref->[0 +]); } else { die qq{not hash/array ref: $dataref}; } } " { key_A => { "6.0" => [ { FILENAME => "filename", ooo => "xxx", VERSION => "version" }, ], }, } filename xxx not hash/array ref: CODE(0x66a6bc) at -e line 1.
Update: Changed code example as follows:
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Can I avoid loops getting the single value from a hash without knowing the key?
by anadem (Scribe) on Jun 12, 2014 at 22:21 UTC |