tags:

views:

139

answers:

5

Hi, 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

+2  A: 

Iterate over keys %HoA, apply grep on each of the arrays (you will have to unreference them with @{$HoA{$key}}), store references to the results back in $HoA{$key}.

Lukáš Lalinský
A: 

Use delete function to delete specific element from the hash .

delete $HoA{flintstones}->[1];

pavun_cool
it gives "NOT an Array reference"
bilal
+10  A: 

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}};
FM
+4  A: 
@{ $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;
Sean
A: 

delete ${${$HoA{flintstones}}[1]}{day};

Pramodh