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

I am writing a piece of code to sanity check various documents. I am currently writing a test to require a field to be non-empty if it is required. I was worried that if did not force grep into a scalar context. Should the following work as expected:
my %required_column = ( organization => [qw(0 1 2 4 6 7 8 12 15 16 17 18)], contact => [qw(0 1 2 3)], service => [qw(0 1 2 3 4 5 6 7 10 11 )], faq => [qw(0 1 2 3 5 )], literature => [qw(0 1 2 11 12 13)] ); sub sanity_check { my ($file, $column, $col_count) = @_; my $file = basename $file; $dcr_type = Gendcr::determine_dcr_type($file); if (not length($column)) { return if grep { $col_count eq $_ } @{$required_column{$dcr_type}} +; } }

Replies are listed 'Best First'.
Re: [perlfunc] does "if" force "grep" into a scalar context?
by broquaint (Abbot) on Oct 24, 2002 at 15:36 UTC
    Yes, if forces grep() into a scalar context, as list context would complicate things horrideously1. So when grep() returns more than 1 match the if suceeds as grep() returns the number of elements which matched true.
    HTH

    _________
    broquaint

    1 yes that would be a made up word

Re: [perlfunc] does "if" force "grep" into a scalar context?
by Zaxo (Archbishop) on Oct 24, 2002 at 15:46 UTC

    grep will act as you expect in an if conditional clause. The number of grepped elements will be taken in bool context. Your statement will return undef if $col_count is equal-as-a-string to any of the listed numbers in the selected array from your hash.

    If this is not behaving as you want, do you want unless instead of if? Do you mean to use numeric comparison?

    After Compline,
    Zaxo

Re: [perlfunc] does "if" force "grep" into a scalar context?
by PodMaster (Abbot) on Oct 25, 2002 at 02:50 UTC
    When in doubt about context, read "List" is a Four-Letter Word.

    I would've kind of thought this would've been incorporated into the perl core pod by now (go figure).

    ____________________________________________________
    ** The Third rule of perl club is a statement of fact: pod is sexy.