Reputation: 221
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);
Upvotes: 2
Views: 1029
Reputation: 5318
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;
Upvotes: 6
Reputation: 57646
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.
Upvotes: 8
Reputation: 6566
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"},
);
Upvotes: 0