Hello brothers and sisters of the monastary,
I need a function which will filter a nested hash, removing any fields I'm not interested in.
For example, lets say my application uses the following data structure. The hash values in any given instance of this structure are variable, but the hash keys will always be the same.
my $source = { f1 => 'garbage', f2 => 'more garbage', f3 => 'important data', f4 => { this => 'sub hash', is => 'garbage' }, f5 => { f6 => 'more important data', f7 => { more => 'garbage', f8 => 'important data', }, f9 => 'garbage', }, f10 => [ 'important', 'data' ], f11 => [ 'more', 'garbage' ] };
I only am interested in the important data, and I want to remove all the garbage.
I came up with a data structure I could use to express the parts of the structure I'm interested in.
my $filter = { f3 => 1, f5 => { f6 => 1, f7 => { f8 => 1 } }, f10 => 1 };
Given this filter, I want the output of the function to be the following hash:
my $output = { f3 => 'important data', f5 => { f6 => 'more important data', f7 => { f8 => 'important data', } }, f10 => [ 'important', 'data' ], };
A key feature of this function is that it must accept any variable type of filter; data which is garbage in one case is important in another case.
I came up with the following function which seems to work well:
sub hash_filter { my $source = shift; my $filter = shift; my %output; foreach ( keys %$filter ) { if ( exists $source->{$_} ) { if ( ref $filter->{$_} eq 'HASH' ) { croak "bad filter: on '$_', expected HASH\n" unless ( ref $source->{$_} eq 'HASH' ); $output{$_} = hash_filter( $source->{$_}, $filter->{$_} ); } else { $output{$_} = $source->{$_}; } } } return \%output; }
I'm very happy with how it works, but since I mean for this function to be reusable I wanted to hear how you all would do it.
Is there a simpler way to do this with higher order functions like map and grep?
Thank you for your help,
Jim
πάντων χρημάτων μέτρον έστιν άνθρωπος.
In reply to A more elegant way to filter a nested hash? by jimpudar
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |