I'm trying to see if keyword_objects has an element {name=>'CRASH', status=>'+'}.
# $bug is a reference to the below data
{
'keyword_objects' => [
bless( { 'name' => 'CRASH', 'status' => '+'}, 'SomeModule::SomeFilename' ),
bless( { 'name' => 'CUSTOMER', 'status' => '-' }, 'SomeModule::SomeFilename' ) ],
'category' => 'error'
}
I couldn't find something like filter in another language so my alternative was using map.
my @isCrash = map { $_->name eq 'CRASH' && $_->status eq '+' } @{ $bug->{keyword_objects} };
The problem with this is that, when there is no such keyword, every time the operation is done, it seems to return an empty value. @isCrash becomes an array of multiple empty values and if(@isCrash) becomes useless. I surely can introduce a new variable which can be changed from the map operation but I feel like there should be a better way to do it. Someone please chime in and share your knowledge.
In Perl (and, indeed, in Unix in general), filter is spelled grep.
my $is_crash = grep { $_->name eq 'CRASH' and $_->status eq '+' }
@{ $bug->{keyword_objects} };
From perldoc -f grep:
grep BLOCK LIST
grep EXPR,LIST[ ... snip ...]
Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value consisting of those elements for which the expression evaluated to true. In scalar context, returns the number of times the expression was true.
So $is_crash will contain the number of elements in your input list where the expression is true. And that can be used as a Boolean value (as zero is false and all other integers are true).
Your code mapped every entry to scalar value of logical expression (true of false).
Try the code below to map it to entry itself for match and empty list for no match.
Sum of multiple empty lists is empty list.
my @isCrash = map { $_->name eq 'CRASH' && $_->status eq '+' ? ($_) : () } @{ $bug->{keyword_objects} };
Alternative approach is to use grep:
# get list of "crashed" elements
my @CrashedList = grep { $_->name eq 'CRASH' && $_->status eq '+'} @{ $bug->{keyword_objects} };
# get number of "crashed" elements in scalar context
my $numberOfCrashes = grep { $_->name eq 'CRASH' && $_->status eq '+'} @{ $bug->{keyword_objects} };
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