Tolgar
asked on
How to return boolean from a grep function in Perl?
Hi,
The following code returns the number of matches:
However, I want to return 1 if there is a match and 0 if there is no match.
How can I do it in one line?
Thanks,
The following code returns the number of matches:
my $name = grep {/tolgar/i} @allNames;
However, I want to return 1 if there is a match and 0 if there is no match.
How can I do it in one line?
Thanks,
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
my $name = !!grep {/tolgar/i} @allNames;
my $name = (grep {/tolgar/i} @allNames)&&1;
my $name = 1-!grep /tolgar/i, @allNames;
my $name = (grep /tolgar/i, @allNames) ? 1 : 0;
should give the equivalent result.
Also, a regex to grep doesn't need to be enclosed in a block - {/tolgar/i} and /tolgar/i should be equivalent. The only difference in syntax is that the regex version has to be followed by a comma (as in my suggested line above).