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?\n";  # 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\n”, 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 ...

Get Perl for C Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.