Question

Just started to learn Perl and namely, learn program flow - main noteable 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");
}
Was it helpful?

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.

OTHER TIPS

Try adding a call to chomp after you get your value from STDIN:

$userName = <STDIN>;
chomp($userName);

Since the value read in from STDIN will have a newline character on the end. The chomp() built-in will remove a newline from the end of a string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top