Hello Perl Monks,
I need some suggestions in filtering out few key value pairs from a hash reference. Here is a quick example that will probably demonstrate what I am trying to do (you will notice that in my final data structure the array of hashes has one key value pair less as it has been moved outside of array):
Lets assume I have a following data structure:
@data = ( { id => '1', name => 'Tom', sex => 'Male', }, { id => '2', name => 'Harry', sex => 'Male', }, { id => '3', name => 'Pam', sex => 'Female', }, { id => '4', name => 'Dick', sex => 'Male', } );
From this array of hashes, I am interested in creating a hash of array of hashes which will have inner key of sex whose value will be array of hashes.
My attempt to do this was as follows:
use strict; use warnings; use Storable qw / dclone /; #my @data = ( ... ) As shown above; my $data2; for my $href ( @data ) { my $copy_ref = dclone($href); my $sex = $copy_ref->{sex}; delete $copy_ref->{sex}; push @{ $data2->{$sex} }, $copy_ref; } use Data::Dumper; print Dumper $data2;
This was the output:
$VAR1 = { 'Female' => [ { 'name' => 'Pam', 'id' => '3' } ], 'Male' => [ { 'name' => 'Tom', 'id' => '1' }, { 'name' => 'Harry', 'id' => '2' }, { 'name' => 'Dick', 'id' => '4' } ] };
I am creating a copy of the hash reference and then manipulating the copy reference and then adding it to new data structure to protect my original data structure. Is there a better way to filter certain key value pairs from a hash reference without having to create a copy reference but protecting the original data structure.
Since this is only for learning purposes, I am interested in looking at other options even if they come at the cost of readability.
Looking forward to your wisdom.
Regards
Jaypal
In reply to How to filter few key value pairs from hash reference by jaypal
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |