I have typed a little program to refresh my Perl knowledge, especially the IF and Else-Case I was interested in. How do I make Perl recognize that the input was empty? I checked the input with "==" and also with "eq" but my program always says "You have typed nothing!".
#!/usr/bin/perl
# input line
$input_line = "";
# terminal input
print "Input:";
$input_line = <STDIN>;
# input verification
print "Your input was: ", "$input_line";
print "\n";
# decider terminal input
if ($input_line == "" or $input_line eq "")
{ print "You have typed nothing!";
print "\n"; }
else
{ print "Typing nothing is bad!";
print "\n"; }
And the output if I type "Hello" is:
Input:Hello
Your input was: Hello
You have typed nothing!
If I type Hello
, then there is input.
If I type nothing, then the output should write "You have typed nothing!", and the Else-Case should also appear.
Always add use warnings;
to your code to get more information as to why it does not work:
Argument "" isn't numeric in numeric eq (==) at ... line ..., line 1.
One approach is to check the length of the string input. It is also a good practice to chomp the input to remove any newline character.
use warnings;
use strict;
# input line
my $input_line = "";
# terminal input
print "Input:";
$input_line = <STDIN>;
chomp $input_line;
# input verification
print "Your input was: ", "$input_line";
print "\n";
# decider terminal input
if (length($input_line) == 0) {
print "You have typed nothing!";
print "\n";
}
It is also good practice to add use strict;
. In this case you need to declare variables with my
.
Since you are new to Perl, refer to the Basic debugging checklist