Skip to content

Instantly share code, notes, and snippets.

@drbaggy
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drbaggy/68f50f6f9661428700fb to your computer and use it in GitHub Desktop.
Save drbaggy/68f50f6f9661428700fb to your computer and use it in GitHub Desktop.
Get all "id" attributes from a data structure!
use strict;
use warnings;
use feature qw(say);
my $data = {
'top' => {
'window' => {
'elements' => [
{ id => 44, name => 'link', value => 'xyz' },
{ id => 48, name => 'title', value => 'Home Page' },
{ id => 100, name => 'author', value => 'Admin' }
],
id => 19
},
'cache' => [
{ id => 199, data => '9E27F645-2B37-46F3-B60C-36B1EFD235A2' },
{ id => 40, data => 'F35FD610-A0AE-4C71-871D-6D19685D01A6' },
{ id => 100, data => { name => 'author', value => 'Admin' } }
],
id => 55
},
id => 1
};
say join q( ), sort { $a <=> $b } get_ids( $data );
sub get_ids {
my $ds = shift;
return 'ARRAY' eq ref $ds ? ( map { get_ids( $_ ) } grep { ref $_ } @{$ds} )
: 'HASH' eq ref $ds ? ( map { ref $ds->{$_} ? get_ids($ds->{$_}) : $_ eq 'id' ? $ds->{$_} : () } keys %{$ds} )
: ();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment