简体   繁体   中英

How do I filter out empty hashes from an array in perl?

I have an array of hashes like so:

my @array = [
             {1 => "Test1"},
             {},
             {1 => "Test2"},
            ];

I try to filter out the {} from this array so that the end result is an array without any {} like so:

my @array = [
             {1 => "Test1"},
             {1 => "Test2"},
            ];

I tried using something like this but it doesn't work:

my @new_array = grep(!/{}/, @array);

The grep command can take a regex as argument, but also an arbitrary block of code. And please do not try to match Perl code with regexes, this doesn't work.

Instead, we ask for the number of keys in the anonymous hash:

my @new_array = grep { keys %$_ } @array;

This selects all hashes in @array where the number of keys is not zero.

1) A small correction:

my @array = [
    {1 => "Test1"},
    {},
    {1 => "Test2"},
];

Is really a 1-element array with array ref inside. You probably need

my @array = (
    {1 => "Test1"},
    {},
    {1 => "Test2"},
);

2) The grep expr:

my @new_array = grep { scalar %$_ } @array;

Hash returns 0 in scalar context if it's empty, and something like "17/32" otherwise. So the grep will only pick non-empty arrays.

UPDATE: As @raina77ow suggests, scalar may be omitted! So it's even shorter (though I still prefer explicit scalar for clarity in my code).

my @new_array = grep { %$_ } @array;

You need something like this:

my @new_array = grep(keys %$_, @array);

The /.../ in your code is a regular expression. It checks if each element in the array contains certain characters. However, your array contains references to hashes, so you need to dereference each element and then see if that is empty.

Also, this declaration is incorrect:

my @array = [
             {1 => "Test1"},
             {},
             {1 => "Test2"},
            ];

The brackets create an array reference, while you just want an array. Just use parentheses instead:

my @array = (
             {1 => "Test1"},
             {},
             {1 => "Test2"},
            );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM