Search code examples
perl

Why isn't eq working with my string input?


Just started to learn Perl and namely, learn program flow - main notable differences between evaluating strings and number and using the appropriate operators. Simple script, I have here is driving me crazy as it's a super simple, if else statement that should on "mike" being entered run and doesn't work. It outputs the else statement instead. Please help

#!C:\strawberry\perl\bin\perl.exe

use strict;
#use warnings;
#use diagnostics;

print("What is your name please?");
$userName = <STDIN>;


if($userName eq "mike"){
    print("correct answer");
}
else{
    print("Wrong answer");
}

Solution

  • As I read your question I thought you were about to have a problem with strings versus numeric values in an equals. Consider the following case:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    print("What is the meaning of life, the universe and everything? ");
    chomp(my $response = <STDIN>);
    
    if ( $response == 42) {
    #if ( 42 ~~ $response ) {
        print "correct answer\n";
    } else {
        print "Wrong answer\n" ;
    }
    

    Try the two different if statements. Answer something nice like family and see what happens. The ~~ is the smart match operator which has helped some of this problem in Perl. Read more about it here (under "smart matching in detail"). Note also the inline use of the chomp operator.