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

I have this conditional statement that I am using inside a foreach loop.
next if @flds[9..13] eq ""; if (defined (@flds[9..13])) { print "$flds[13]L\n"; &add_sub (); print "</tr>\n"; }
I want this statement to evaluate five data fields in an array, if all five are available then run the sub, even if any one is available run the sub, else exit conditional. It simple enough but I cant seem to get it right. Thanks in advance...

Replies are listed 'Best First'.
Re: simple condition
by TheoPetersen (Priest) on Sep 25, 2001 at 01:11 UTC
    I don't understand the two conditions, so I'll try one each way. Suppose we have a foreach loop that loads @flds based on some other array of values, @vals. If all five fields are available then run the sub:
    OUTER_LOOP: foreach my $val (@vals) { @flds = something to do with $val; foreach my $check (@flds[9..13]) { next OUTER_LOOP unless $check; } &add_sub (): print "</tr>\n"; }
    If any one is available then run the sub:
    foreach my $val (@vals) { @flds = something to do with $val; my $go_ahead; foreach my $check (@flds[9..13]) { if ($check) { $go_ahead = 1; last; } } if ($go_ahead) { &add_sub (); print "</tr>\n"; } }
    Something like that?
Re: simple condition
by perrin (Chancellor) on Sep 25, 2001 at 01:13 UTC
    Maybe you should use grep.
    if (scalar(grep {defined} @flds[9..13])) { # do this if any are defined }
    Hmmm... looks a little obfuscated. It could probably be prettier.
Re: simple condition
by herveus (Prior) on Sep 25, 2001 at 06:08 UTC
    Howdy!

    @flds[9..13] eq "" won't do what you might think.

    @flds[9..13] evaluates to $flds[13] in a scalar context, so it only tests the last field of the five.

    Similarly, defined(@flds[9..13]) only tests the defined-ness of $flds[13].

    From the code, I would infer that "available" means not the empty string. Based on that, I might try:

    next unless grep($_ eq '', @flds[9..13]) == 5; print...
    yours
    Michael

    Edit kudra, 2001-09-26 Replaced [ and ] outside of code tags with entities