Programmatically read from STDIN or input file in Perl

What is the slickest way to programatically read from stdin or an input file (if provided) in Perl?


Solution 1:

while (<>) {
print;
}

will read either from a file specified on the command line or from stdin if no file is given

If you are required this loop construction in command line, then you may use -n option:

$ perl -ne 'print;'

Here you just put code between {} from first example into '' in second

Solution 2:

This provides a named variable to work with:

foreach my $line ( <STDIN> ) {
    chomp( $line );
    print "$line\n";
}

To read a file, pipe it in like this:

program.pl < inputfile

Solution 3:

The "slickest" way in certain situations is to take advantage of the -n switch. It implicitly wraps your code with a while(<>) loop and handles the input flexibly.

In slickestWay.pl:

#!/usr/bin/perl -n

BEGIN: {
  # do something once here
}

# implement logic for a single line of input
print $result;

At the command line:

chmod +x slickestWay.pl

Now, depending on your input do one of the following:

  1. Wait for user input

    ./slickestWay.pl
    
  2. Read from file(s) named in arguments (no redirection required)

    ./slickestWay.pl input.txt
    ./slickestWay.pl input.txt moreInput.txt
    
  3. Use a pipe

    someOtherScript | ./slickestWay.pl 
    

The BEGIN block is necessary if you need to initialize some kind of object-oriented interface, such as Text::CSV or some such, which you can add to the shebang with -M.

-l and -p are also your friends.