Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello, if you have an array, with say 3 elements, is there a way to check if this array has at least one word?
Consider:
@array=(" ",jim," "," ")

I mean, how can you ask in perl : "If at least one element is not empty string, then print OK"?

Replies are listed 'Best First'.
Re: Check if one of the array elements is not empty
by toolic (Bishop) on Nov 11, 2009 at 02:15 UTC
      And the nice thing about List::MoreUtils::any is
      1. that it will return as soon as it found a "match" in the array and does not have to run through all elements as grep does;
      2. it can take any function or subroutine as an argument to match, not only a regex.
      .

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

        ad 1. on other side, grep in scalar content returns number of matching elements, so you can do tests like "at least N elements match"
        ad 2. same you can do with grep
Re: Check if one of the array elements is not empty
by markkawika (Monk) on Nov 11, 2009 at 01:12 UTC

    Well if you're defining "not an empty string" to mean "a string containing something other than whitespace", then this is the simplest way:

    if (grep /\S/, @array) { print "OK\n"; }

    You can modify the regular expression to match whatever you want to match.

Re: Check if one of the array elements is not empty
by 7stud (Deacon) on Nov 11, 2009 at 02:12 UTC

    Just for clarification, there is a difference between an empty string("") and a string with one space(" "):

    use strict; use warnings; use 5.010; my @array=("", "jim"," "); foreach my $str (@array) { if ($str) { say "perl considers the string: -->$str<-- to be true."; }else { say "perl considers the string: -->$str<-- to be false."; } } output: perl considers the string: --><-- to be false. perl considers the string: -->jim<-- to be true. perl considers the string: --> <-- to be true.
      Also, depending on how @array is actually populated, some elements may be undefined, which perl also treats as false, and throws a warning (if use warnings is in effect) if you try to do anything with it...

      Use of uninitialized value in concatenation (.) or string at test2.pl +line 15. perl considers the string:--><-- to be false.
Re: Check if one of the array elements is not empty
by rovf (Priest) on Nov 11, 2009 at 10:14 UTC