Reputation: 9049
I'd like a Perl script that I'm writing to display a help message if it receives no input.
How can I tell if nothing is coming in on stdin?
Upvotes: 3
Views: 6475
Reputation: 386501
It's possible to check if something has come in on STDIN (using a nonblocking read, select
or ioctl FIONREAD
), but it's impossible to check if something is coming in on stdin, since it hasn't happened yet.
Impossibility aside, you're asking to break convention. For example, take cat
, perl
, sort
, etc, etc. If you provide no arguments, they'll happily wait on STDIN until you provide what they need.
The user knows to use man tool
or tool --help
to get info.
Upvotes: 0
Reputation: 924
If you are talking about input from STDIN, you can check if the variable is equal to the empty string (after removing the CR/LF). For example:
my $myInput = <STDIN>;
chomp($myInput);
if ($myInput eq "")
{
print "Error! You didn't submit any data!\n";
}
However, as @thnee says, if you are checking for the arguments passed in via command line, you should use $#ARGV.
For example:
if ($#ARGV == -1)
{
print "Error! No input arguments entered!\n";
exit(-1);
}
References:
http://perldoc.perl.org/functions/chomp.html
http://perldoc.perl.org/perlvar.html
Upvotes: 1
Reputation: 129
You might also find this perldoc FAQ useful for checking whether there is any input from the keyboard:
http://perldoc.perl.org/perlfaq8.html#How-do-I-check-whether-input-is-ready-on-the-keyboard%3f
Upvotes: 0
Reputation: 80433
if (@ARGV == 0 && -t STDIN && -t STDERR) {
print STDERR "$0: WARNING: reading input from keyboard, type ^D for EOF, ^C to intr.\n";
}
Upvotes: 8
Reputation: 5927
$#ARGV
contains the number of arguments.
http://www.devdaily.com/perl/perl-command-line-arguments-read-args
Upvotes: 0