Reading Input

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.

Listing 2.3. name1.pl
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>;

reads everything you type and puts it in $name—everything! If you type "Steve<Enter>", that’s what gets put in $name. In Perl terms, the variable $name has the value “Steve ”.

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.

Listing 2.4. name2.pl
use strict; 
use warnings; 
my $name;         # Name of the user 
print "Enter name: "; 

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

print "Hello $name. How are you?
";

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset