Pages

Getting input from keyboard

We have written a lot of stuff to the standard output, in the previous Perl examples, now it's time to start getting some input from the standard input.

Nothing easier than that. Here is an improved Hello program that even ask to the user for a name:

print "Input your name: ";
my $name = <STDIN>;
print "Hello, $name!\n";

Actually, this was a buggy example. The fact is that the line we got from standard input includes the newline at its end. We could solve this problem passing the string to the chomp() function, the check for newline at its end and trim them off:

chomp($name);
print "Hello, $name!\n";

But why should we put reading and trimming in two different lines? Won't it be clearer for the reader this?

print "Input your name: ";
chomp(my $name = <STDIN>);
print "Hello, $name!\n";

And if we really want to save some typing, why should we specify STDIN. We normally expect to read data from there so, as usual in Perl, default could be omitted:

print "Input your name: ";
chomp(my $name = <>);
print "Hello, $name!\n";

No comments:

Post a Comment