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

$fields[6] = '"KBBM"'; if (@fields[6] =~ ('"KOTB"' or '"KBBA"' or '"KBBC"' or '"KBBM"' or '"K +BBT"')) { print "Inside the Check" }
The array value itself contains double quote in it. is the if condition which i write is correct ?

Replies are listed 'Best First'.
Re: is this right ?
by Corion (Patriarch) on May 05, 2008 at 09:20 UTC

    The logic expression will likely not do what you want. But as you haven't told us what you actually want to do, it's kinda hard to guess. What do you consider "correct"?

    Most likely, you want:

    if ( $fields[6] eq '"KOTB"' or $fields[6] eq '"KBBA"' ... or $fields[6] eq '"KBBT"') { print "Inside the Check" }

    ... but again, you should tell us more about what you have, what happens, what you expect to happen, and what you've tried so far.

Re: is this right ?
by moritz (Cardinal) on May 05, 2008 at 09:21 UTC
    It just doesn't look right. You are trying to use junctions, which are not available in Perl 5.

    If you have perl 5.10.0, you can use smart match instead:

    if ($fields[6] ~~ qw("KOTB" "KBBA" "KBBC" "KBBM" "KBBT")){ ... }

    Or you can use a regex match (with any perl version):

    if ($fields[6] =~ m/\A"(?:KOTB|KBB[ACMT])"\z/){ .... }
Re: is this right ?
by FunkyMonk (Bishop) on May 05, 2008 at 10:17 UTC
    As others have said, you can't write ifs like that in Perl 5. Depending on exactly what it is you want, here's another way
    for ( '"KOTB"', '"KBBA"', '"KBBC"', '"KBBM"', '"KBBT"' ) { if ( $fields[6] eq $_ ) { # do something } }

    @fields[6] is better written $fields[6] (warnings should have told you about that). @fields[6] an array slice that's described in perldata.


    Unless I state otherwise, all my code runs with strict and warnings
Re: is this right ?
by apl (Monsignor) on May 05, 2008 at 11:32 UTC
    Or you could use the five values as keys in %hash, and simply test
    if ( defined( $hash{ $fields[6] } ) { # do something }
Re: is this right ?
by swampyankee (Parson) on May 05, 2008 at 11:58 UTC

    No. You could use any from List::MoreUtils or something like this:

    if(grep{ /$fields[6]/ ('"KOTB"', '"KBBA"','"KBBC"' , '"KBBM"' , '"KBB +T"')}) { &do_this; else { &do_something_else; }
    Note:  example code only; not tested in any way, manner, or form.


    Information about American English usage here and here. Floating point issues? Please read this before posting. — emc