Search object array for matching possible multiple values using different comparison operators
Posted
by Sparkles
on Stack Overflow
See other posts from Stack Overflow
or by Sparkles
Published on 2010-05-14T01:04:42Z
Indexed on
2010/05/14
1:14 UTC
Read the original article
Hit count: 303
I have a function to search an array of objects for a matching value using the eq operator, like so:
sub find {
my ( $self, %params ) = @_;
my @entries = @{ $self->{_entries} };
if ( $params{filename} ) {
@entries = grep { $_->filename eq $params{filename} } @entries;
}
if ( $params{date} ) {
@entries = grep { $_->date eq $params{date} } @entries;
}
if ( $params{title} ) {
@entries = grep { $_->title eq $params{title} } @entries;
}
....
I wanted to also be able to pass in a qr quoted variable to use in the comparison instead but the only way I can think of separating the comparisons is using an if/else block, like so:
if (lc ref($params{whatever}) eq 'regexp') {
#use =~
} else {
#use eq
}
Is there a shorter way of doing it? Because of reasons beyond my control I'm using Perl 5.8.8 so I can't use the smart match operator.
TIA
© Stack Overflow or respective owner