toolic has already given the correct answer, but I wanted to throw in some beginner advice.
Your code can be condensed down to this:
use strict;
use warnings; # always use these two pragmas
print "Input: ";
chomp (my $input_line = <>);
print "Your input was: '$input_line'\n";
if (length $input_line == 0) {
print "You have typed nothing!\n";
}
- Remove initialization and pre-assigning "". No
$input = ""
- Variables are already empty when created, and even so, when you assign to them,
any previous content is deleted.
print "Input: "; # extra space to make it look nicer
chomp (my $input_line = <>); # chomp can be used directly on init and assignment
- Instead of
<STDIN> we can use <>, which chooses either STDIN, or file input as necessary
print "Your input was: '$input_line'\n";
- You don't need a new print for
\n, nor a new quote for a variable
- Variables don't need to be quoted
- Adding
'' around the variable shows more context, especially with space and empty string
- You can also use say, which adds a newline to print. Enable with:
use feature 'say';
say "Your input was: $input"; # no \n needed
A very good module for debugging is Data::Dumper. It is a core module, so no installation required. It will show you the content of a variable
use Data::Dumper;
print Dumper $input_line;
# Will print: $VAR1 = '';
While the below is a good solution for normal answers:
if (length($input_line) == 0) {
print "You have typed nothing!\n";
}
What if someone answers with a space (not empty), or you forget to add chomp? You can for example be more specific by using a regex:
if ($input !~ /\S/) # no non-whitespace
if ($input !~ /^[abcd]+$/) # contains something other than what you need, e.g. abcd
if ($input =~ /[^abcd]/) # alternative phrasing
A few examples for more studies. Good luck!
As ikegami says, it is possible to enter eof only to the program (by for example pressing Ctrl-D (unix) or Ctrl-Z (win) at the prompt), causing readline to return undef to the input variable. In which case the program issues a few undefined warnings for the different operations. To resolve this, you could change your input readline chomp (my $input.... to:
my $input_line = <>;
if (! defined $input_line) {
die "Input required.";
}
chomp $input_line;
Which is a bit more complicated, but will prevent warnings for this edge case.
==converts both operands to a number (i.e.0for input Hello), and 0 == 0. Use onlyeq(but all that is explained in the duplicate)