4n0n9m0u5
4n0n9m0u5

Reputation: 13

basic perl conditional script not working

I am a beginner to perl and have just been messing around trying to create little scripts. I'm not sure what is wrong here but it just falls through to the else every time as if nothing I input satisfies the if or elsif conditions. Is it because eq is the wrong operator? Or is there something else wrong in my code? Thanks!

#!/usr/bin/perl
use strict;
use warnings;
print "what is your name?\n";
my $name = readline STDIN; 
print "Hello $name How are you today?\n";

my $feeling = readline STDIN;

if ($feeling eq "happy") {
    print "that's good!\n";
}
elsif ($feeling eq "good") {
    print "okay!\n";
}
else {
    print "Interesting\n";
}

Upvotes: 1

Views: 90

Answers (2)

vol7ron
vol7ron

Reputation: 42109

chomp is used to "chomp off" the input record separator, which by default is a newline character.

#!/usr/bin/perl

use strict;
use warnings;
use 5.012;                               # to use things like 'say' and 'given'

say "what is your name?";                # 'say' is like 'print', but means you don't have to use '\n'

my $name = <STDIN>;                      # good to include angled brackets <>
chomp($name);                            # remove the newline when entering the number

say qq{Hello $name, how are you today?}; # qq{} acts like double-quotes ("")

my $feeling = <STDIN>;
chomp $feeling;                          # notice parenthese aren't always needed
                                         # you could also do chomp(my $feeling=<STDIN>);

given (lc $feeling){                     # 'given' is Perl's version of a Switch and lc makes input lowercase
   when('happy') { say q{That's good.} } # q{} acts like single-quotes ('')
   when('good')  { say q{Okay!}        }
   default       { say q{Interesting}  } # your else-case
}

As the warnings suggest, given is experimental until smartmatch is figured out. It is perfectly acceptable to use the if-elsif-else structure, if you choose.

Upvotes: 0

Pramod Shinde
Pramod Shinde

Reputation: 1892

Use chomp($feeling);

#!/usr/bin/perl
use strict;
use warnings;
print "what is your name?\n";
my $name = readline STDIN;
chomp($name);
print "Hello $name How are you today?\n";

my $feeling = readline STDIN;

chomp($feeling);
if ($feeling eq "happy") {
 print "that's good!\n";
}
elsif ($feeling eq "good") {
 print "okay!\n";
}
else {
 print "Interesting\n";
}

readline STDIN captures every character typed along with last enter hit as \n, say if you type "happy" and hit enter for $feeling then its accepted as "happy\n" notice \n is because enter hit to remove last \n newline character use chomp removes any trailing string

Upvotes: 2

Related Questions