[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to return boolean from a grep function in Perl?

Posted on 2011-10-21
5
Medium Priority
?
326 Views
Last Modified: 2012-05-12
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,
0
Comment
Question by:Tolgar
  • 3
5 Comments
 
LVL 3

Accepted Solution

by:
varontron earned 2000 total points
ID: 37009361
Try the ternary conditional:
my $name = (grep {/tolgar/i} @allNames) > 0 ? 1 : 0;

Open in new window


Dave
0
 
LVL 27

Expert Comment

by:wilcoxon
ID: 37009379
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).
0
 
LVL 85

Expert Comment

by:ozo
ID: 37009461
my $name = !!grep {/tolgar/i} @allNames;
0
 
LVL 85

Expert Comment

by:ozo
ID: 37009482
my $name = (grep {/tolgar/i} @allNames)&&1;
0
 
LVL 85

Expert Comment

by:ozo
ID: 37009505
my $name = 1-!grep /tolgar/i, @allNames;
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question