Link to home
Start Free TrialLog in
Avatar of Tolgar
Tolgar

asked on

How to return boolean from a grep function in Perl?

Hi,
The following code returns the number of matches:

my $name = grep {/tolgar/i} @allNames;

Open in new window


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
Avatar of varontron
varontron
Flag of Afghanistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wilcoxon
varontron has the simplest solution.  One further simplification would be to leave out the "> 0":

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).
my $name = !!grep {/tolgar/i} @allNames;
my $name = (grep {/tolgar/i} @allNames)&&1;
my $name = 1-!grep /tolgar/i, @allNames;