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

Hi Monks I have a simple perl script
#! /usr/bin/perl while(<DATA>) { chomp($_) ; if ( $_ == "aaaa" ) { print "$_\n" ; } else { print "OK\n" ; } } __DATA__ aaaa bbbb cccc dddd
Running it gives
aaaa bbbb cccc dddd
I expected
aaaa OK OK OK
Any help would be appreciated!

Replies are listed 'Best First'.
Re: if statement not working
by GrandFather (Saint) on Feb 08, 2009 at 09:12 UTC

    Always use strictures (use strict; use warnings;)! If you turn strictures on you will get the warning:

    Argument "aaaa" isn't numeric in numeric eq (==) at ...

    Use the string equality operator (eq) for comparing strings. The numeric equality operator (==) will "numify" its operands and non-numeric strings numify to 0.


    Perl's payment curve coincides with its learning curve.
Re: if statement not working
by alienmonk (Initiate) on Feb 08, 2009 at 09:42 UTC
    Just a small change in your code if ( $_ == "aaaa" ) , you are comparing characters so it should be if ( $_ eq "aaaa" ) Now it should work.
Re: if statement not working
by Anonymous Monk on Feb 08, 2009 at 09:12 UTC
    fixed it, for stings perl uses eq
Re: if statement not working
by salazar (Scribe) on Feb 08, 2009 at 23:52 UTC
    Yeah Perl is different from the other languages I've worked with in that == is type-specific, use
    eq - equal to ne - not equal to
    for strings, as suggested above.