purple.mojo has asked for the wisdom of the Perl Monks concerning the following question:

Hello all, I'm learning perl for my job.

given this code:

@array = qw(apple pear banana orange grape); @array2 = grep {$_ =~ "n"} @array; print "@array2\n";
How do I code this into an "if" statement? So... "if the grep conditions are true, print what's indicated, otherwise print a message that says, "nothing found".

Thanks

Replies are listed 'Best First'.
Re: grep and arrays
by pc88mxer (Vicar) on Apr 14, 2008 at 23:27 UTC
    @array2 will be empty if there are no matches. A way to test this condition is:
    if (@array2) { # array2 is not empty } else { # array2 is empty }
    Used in this way, @array2 returns its size. So, you can write tests like this:
    if (@array2 > 3) { # array2 has more than three elements }
    The first test is short-hand for if (@array2 != 0) { ....
Re: grep and arrays
by jwkrahn (Abbot) on Apr 14, 2008 at 23:58 UTC

    @array2 = grep {$_ =~ "n"} @array; is usually written as @array2 = grep /n/, @array; and if you want to use that in an "if" statement:

    if ( grep /n/, @array ) { print "\@array has some elements that contain 'n'.\n"; } else { print "\@array does not have 'n' in any elements.\n"; }
Re: grep and arrays
by FunkyMonk (Bishop) on Apr 14, 2008 at 23:08 UTC
    What have you tried so far, and what result did it give? If you've tried, and got nowhere, where did you get stuck?

    I'm sure someone will give you an answer, but you'll quick a quicker response by putting some effort into a solution.

Re: grep and arrays
by NetWallah (Canon) on Apr 15, 2008 at 00:07 UTC
    Another way, without "if":
    :~$ perl -e ' @array = qw(apple pear banana orange grape); print join + (" ", grep /n/, @array)|| "Not Found","\n";'

         "How many times do I have to tell you again and again .. not to be repetitive?"

Re: grep and arrays
by apl (Monsignor) on Apr 15, 2008 at 01:10 UTC
Re: grep and arrays
by j1n3l0 (Friar) on Apr 15, 2008 at 08:42 UTC
    Something like this:

    my @array = qw(apple pear banana orange grape); if ( my @matches = grep /n/, @array ) { print "@matches\n"; } else { print "NOTHING FOUND\n"; }


    Smoothie, smoothie, hundre prosent naturlig!
Re: grep and arrays
by Anonymous Monk on Apr 15, 2008 at 14:17 UTC