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

I am trying to do a case insensitive string compare such as follows but am not getting the correct results. What am I missing? Much thanks in advance.
use strict; my $test="yes"; print "test=$test\n"; if ($test eq /yes/i) { print "yes\n"; }else{ print "no\n"; }

Replies are listed 'Best First'.
Re: Case insensitive string compare
by pzbagel (Chaplain) on Aug 09, 2003 at 04:52 UTC

    You need to use the =~ notation to check the regex.

    if ($test =~ /yes/i)

    The eq operator is the string comparison operator. You can use it to match a string exactly.

    HTH

Re: Case insensitive string compare
by Kanji (Parson) on Aug 09, 2003 at 05:13 UTC

    As pzbagel noted, you need =~ to match against your regex, although I'd modify your regex to be /^y(es)?$/ to allow for both 'yes' and 'y' as valid answers.

    Alternately, and if 'yes' is the ONLY valid answer, then you can use an eq comparison by forcing the case of your input with lc().

    if( lc($test) eq 'yes' ) { ... }

        --k.


Re: Case insensitive string compare
by diotalevi (Canon) on Aug 09, 2003 at 13:07 UTC

    Or!!! Use the \L escape.

    use strict; my $test="yes"; print "test=$test\n"; if ($test eq "\Lyes") { print "yes\n"; }else{ print "no\n"; }
Re: Case insensitive string compare
by NetWallah (Canon) on Aug 09, 2003 at 16:23 UTC
    Expanding on diotalevi's solution, to allow for the case where $test may be mixed-case, I would write:
    use strict; my $test="yes"; print "test=$test\n"; if ("\L$test" eq "yes") { # No need to L-case the constant print "yes\n"; }else{ print "no\n"; }
    Anyhow I'd prefer to use the reqular-expression match, as indicated by pzbagel.