in reply to howto map/grep a complex structure
Here is a way. You can also write a more customized sub for your data structure. Not sure if this passes the test for elegant though :)#!/usr/bin/env perl use strict; use warnings; use Data::Dump; sub collectLeaves ($) { my ( $ds, $leaves ) = @_; $leaves = defined($leaves) ? $leaves : []; if ( ref $ds eq 'ARRAY' ) { &collectLeaves( $_, $leaves ) for ( @{$ds} ); } elsif ( ref $ds eq 'HASH' ) { &collectLeaves( $ds->{$_}, $leaves ) for ( keys %{$ds} ); } else { push @{$leaves}, $ds; } return @{$leaves}; } my $hash = { key1 => [ 3,4,5,6 ], key2 => [ 7,8,9,10 ], key3 => [ d1 => { 42 => [ 'blue' ], 58 => [ 7 ], } ] }; my @wanted = grep { $_ == 7 } collectLeaves $hash; dd @wanted; # (7, 7)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: howto map/grep a complex structure
by stevieb (Canon) on Aug 27, 2015 at 12:50 UTC | |
by AnomalousMonk (Archbishop) on Aug 27, 2015 at 14:03 UTC | |
by trippledubs (Deacon) on Aug 27, 2015 at 21:50 UTC | |
by AnomalousMonk (Archbishop) on Aug 28, 2015 at 17:01 UTC | |
by trippledubs (Deacon) on Aug 27, 2015 at 20:16 UTC |