Perl Stdin -- Reading User Input in Perl

Getting user input is easy in Perl, as long as you're happy to wait for the user to hit <return>.

The following little program waits for the user to enter a string and hit the return key, then tells the user what he entered.

use strict; 
use warnings; 

sub main
{
    my $input = <STDIN>;
    
    print "You entered: $input";
}

main();





hello
You entered: hello







Cleaning Up Input From Stdin in Perl



There's a little complication with the above program, which becomes apparent if we surround the input string with quotes before echoing it back. We get the following output:

hello
You entered: 'hello
'




You can see that the input string includes the carriage return character that the user had to enter in order to get the program to accept the input.

A common way of dealing with this is to use chomp on the user input to discard the last character.

use strict; 
use warnings; 

sub main
{
    my $input = <STDIN>;
    
    chomp $input;
    
    print "You entered: '$input'";
}

main();





hello
You entered: 'hello'




Personally I prefer to use a regular expression to clean newline and other characters from the input.

use strict; 
use warnings; 

sub main
{
    my $input = <STDIN>;
    
    $input =~ s/[\n\r\f\t]//g;
    
    print "You entered: '$input'";
}

main();





hello
You entered: 'hello'




In the above program, I've used a regular expression to remove all carriage returns, line feeds and tabs.

Using Stdin to Read Input From Files in Perl



One great use of <STDIN> is to read input quickly from a file in Perl. Of course a longer and better way of doing this would be to open the file, then use the file handle in place of STDIN. But sometimes you just want a quick solution.

Let's say we call the program above perltest.pl; suppose we have the text "This file contains some text." in a file called temp.txt; then we can do the following in both Windows and UNIX or Linux:

C:temp>perl perltest.pl < "temp.txt"
You entered: 'This file contains some text.'




The < operator simply directs STDIN to the Perl program, which reads it as if a user had typed it directly and pressed the enter key.