Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, How to delete a hash in array of hashes?

Tags:

arrays

hash

perl

I have an Array of Hashes as below.

@students= (
    {
        'math' => 95,
        'phy'  => 90,
        'che'  => 85
    },
    {
        'math' => 50,
        'phy'  => 70,
        'che'  => 35
    }
);

I want to delete a entire hash based on some conditions, for that i tried with below code but am getting an error saying delete argument is not a HASH or ARRAY element or slice. So please help me, how can i do?

for $i ( 0 .. $#students) {
    for $key ( keys %{ $students[$i] } ) {
        if ($key eq 'che') {
            if ($students->{$key} == 35){
                delete (%{$students[$i]});
            }
        }
    }
}
like image 365
ImDrPatil Avatar asked Jan 11 '23 14:01

ImDrPatil


1 Answers

Deleting is well suited for hash keys, but in your case you want to remove array elements so grep filtering could be applied:

@students = grep { $_->{che} != 35 } @students;
like image 97
mpapec Avatar answered Jan 21 '23 07:01

mpapec