You can read input from the “standard in” using the following statement:
$variable = <STDIN>;
This reads an entire line, up to and including the newline (just like the C fgets function).
Listing 2.3 shows an example.
use strict; use warnings; my $name; # Name of the user print "Enter name: "; $name = <STDIN>; print "Hello $name. How are you? "; # Send name to STDOUT |
The output of this program looks like this:
Enter name: Steve Hello Steve . How are you?
The problem is that when you read the name, you get “Steve ”, instead of “Steve”. That’s because the statement
$name = <STDIN>;
But what you really want is “Steve”, so you need to strip off the last character. This problem is so common that Perl has a special function called chomp whose job is to strip newlines off the ends of strings.
Listing 2.4 shows the program revised to make it work properly.
use strict; use warnings; my $name; # Name of the user print "Enter name: "; $name = <STDIN>; chomp($name); print "Hello $name. How are you? "; |