how can i delete an element from the following hash of arrays;
%HoA = (
flintstones => [ {day=>'19'}, {day=>'21'}, {day=>'22'} ],
jetsons => [ {day=>'29'}, {day=>'23'}, {day=>'25'} ],
simpsons => [ {day=>'26'}, {day=>'33'}, {day=>'27'} ]
);
Like how can i delete e.g {day=>'21'}
from flintstones
and make the result look like;
%HoA = (
flintstones => [ {day=>'19'}, {day=>'22'} ],
jetsons => [ {day=>'29'}, {day=>'23'}, {day=>'25'} ],
simpsons => [ {day=>'26'}, {day=>'33'}, {day=>'27'} ]
);
I have tried using Hash = (); but that results in undef,
in place of the element that i delete
Among all of the Perl’s nested structures, a Multidimensional hash or Hash of Hashes is the most flexible. It’s like building up a record that itself contains a group of other records. The format for creating a hash of hashes is similar to that for array of arrays.
To traverse through the multidimensional hash or to go through each value in a hash, simply loop through the keys of the outer hash and then loop through the keys of the inner hashes. For N-dimension hash, N nested or embedded loops are required to traverse through the complete hash. Both For and While loops can be used to loop over to the hash.
Perl gives you a handy way to get the keys of a hash as an array: Hashes, unlike arrays, are not ordered, so if you want things in some order, you'll need to implement that. A sort on the keys is a common way of doing that.
To traverse through the multidimensional hash or to go through each value in a hash, simply loop through the keys of the outer hash and then loop through the keys of the inner hashes. For N-dimension hash, N nested or embedded loops are required to traverse through the complete hash.
If you know that you want to remove the [1]
element from the flintstones array, you can use splice
directly:
splice @{$HoA{flintstones}}, 1, 1;
If you simply know that you want to remove elements having day = 21, use grep
either in this way:
$HoA{flintstones} = [ grep { $_->{day} != 21 } @{$HoA{flintstones}} ];
Or in this better way, as suggested by Sean's answer:
@{$HoA{flintstones}} = grep { $_->{day} != 21 } @{$HoA{flintstones}};
@{ $HoA{flintstones} } = grep { $$_{day} != 21 } @{ $HoA{flintstones} };
This has the advantage over just assigning a fresh arrayref to $HoA{flintstones}
that existing references to $HoA{flintstones}
(if any) will all continue to refer to the array in %HoA
.
Or, more readably:
my $flintstones = $HoA{flintstones};
@$flintstones = grep { $$_{day} != 21 } @$flintstones;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With