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

I've been working with Perl for a few months now and have found this site to be extremely helpful. I like working with STDIN so that I can make scripts that interact with the cmd prompt. I have a very simple problem I'm trying to solve. When I use something like this...
while (<STDIN>) { chomp; print "$_\n"; }
...it does the job. But it isn't smart enough to prompt me if I forget to pipe a file into it. I'd really like some suggestions about how to check if piped data is waiting from STDIN so that I can prompt when it hasn't been called properly.

Replies are listed 'Best First'.
Re: Need help working with STDIN
by jdporter (Paladin) on Feb 04, 2003 at 17:32 UTC
    Probably the simplest thing to do is to test whether STDIN is connected to a tty, using the -t operator.
    sub prompt { -t STDIN and print "\n? "; } while ( prompt(), defined($_=<STDIN>) ) { chomp; print "$_\n"; }

    jdporter
    The 6th Rule of Perl Club is -- There is no Rule #6.

Re: Need help working with STDIN
by pfaut (Priest) on Feb 04, 2003 at 17:39 UTC

    You can use -t STDIN to see if input is coming from a terminal and print your prompt if it is.

    sub readprompt { my $prompt = shift; print $prompt if -t STDIN; <>; } while (my $i=readprompt(">>")) { print "You said: $i\n"; }
    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';
Re: Need help working with STDIN
by Zio (Novice) on Feb 04, 2003 at 18:11 UTC
    Thanks all!

    The -t was the hint I needed to get things to work.
Re: Need help working with STDIN
by hardburn (Abbot) on Feb 04, 2003 at 17:29 UTC

    Hrm, most *nix programs will just sit there waiting for input. I think any semi-experianced *nix user would expect this behavior. Just make sure you document it's behavior and let the user take care of the rest.

    ----
    Invent a rounder wheel.

Re: Need help working with STDIN
by Anonymous Monk on Feb 05, 2003 at 04:07 UTC
    before the while loop: if (-t STDIN) { do stuff if not piped a file } else { #your while loop processes piped files here while (<STDIN>) { chomp; print "$_\n"; } } chris_piechowicz@hotmail.com