Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I've been using <> for years to read STDIN, but have not found a good way to document my code for others to use.

I want to do something like this (but it doesn't work :) ):
my @lines; foreach my $line (<>) { chomp($line); push(@lines,$line); } if ($#lines<0) { &usage(); } else { #Process STDIN.... } sub usage { printf "This is how to use this script....\n"; die(); }

Replies are listed 'Best First'.
Re: How to use <> responsibly?
by rjt (Curate) on Jul 24, 2013 at 17:12 UTC

    The problem is, if you want your script to read STDIN, and they don't pipe anything in or supply filenames to read, it's going to hang waiting for input. Instead, how about this sort of typical usage, where you supply a `-' as the filename to indicate you'll be supplying input from STDIN instead:

    my $filename = shift // die "Usage: $0 <filename | ->\n"; my $fh = *STDIN; if (filename ne '-') { open $fh, '<', $filename or die "Can't open $filename: $!"; } while (<$fh>) { # Process lines of input }

    Edit: Me fail English? That's unpossible!

    Alternately, simpler structure with autodie and re-opening STDIN instead:

    use 5.012; use warnings; use autodie; my $filename = shift // die "Usage: $0 <filename | ->\n"; open STDIN, '<', $filename if $filename ne '-'; while (<STDIN>) { ... }
Re: How to use <> responsibly?
by jeffa (Bishop) on Jul 24, 2013 at 17:09 UTC

    I find explicitness to aid in self-documentation, so why not specify which handle you are reading and never rely on the implicit default?

    for my $line (<STDIN>) { ... }

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)