How to return boolean from a grep function in Perl?

Posted on 2011-10-21
Last Modified: 2012-05-12
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?

Question by:Tolgar
    LVL 3

    Accepted Solution

    Try the ternary conditional:
    my $name = (grep {/tolgar/i} @allNames) > 0 ? 1 : 0;

    Open in new window

    LVL 26

    Expert Comment

    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).
    LVL 84

    Expert Comment

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

    Expert Comment

    my $name = (grep {/tolgar/i} @allNames)&&1;
    LVL 84

    Expert Comment

    my $name = 1-!grep /tolgar/i, @allNames;

    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    Join & Write a Comment

    On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
    There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
    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…
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…

    728 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

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now