On 8/13/07, Jeff Pang <[EMAIL PROTECTED]> wrote: > > > -----Original Message----- > >From: [EMAIL PROTECTED] > >Sent: Aug 14, 2007 3:20 AM > >To: beginners@perl.org > >Subject: piping and reading stdin > > > >I want to read from a pipe in my perl script invoked like: > > > >date | perl myperlscript.pl > > > >I understand that this puts the text outputted from the date program > >into the stdin. How could I check the buffer contained by the stdin > >without it blocking for you to input anything from the keyboard if > >nothing was piped in to the command. > > > >my perlscript contains something like: > > > >#this part im unsure about so im using functions that dont exist > >if(buffer_has_stuff_in_it(STDIN)){ > > while(<STDIN>){ > > print "$_\n"; > > } > >} > >else{ > > print "You didnt pipe anything into this program!\n"; > >} > > > > Hi, > > You need an IO::Select object to be monitored,if it's timeouted,then die or > exit. > Just show my sample codes,hope this helps. > > use strict; > use IO::Select; > > my $timeout=1; # wait for 1 second > > open PIPE,'cat|' or die $!; # since 'cat' doesn't input anything,program > would die after 1 sec. > my $oldhd=select PIPE;$|++;select $oldhd; > my $s = IO::Select->new(); > $s->add(\*PIPE); > if (my @ready = $s->can_read($timeout)) { > my @content=<PIPE>; > print @content; > }else { > die "no input\n"; > } > close PIPE; snip
Another method is to use turn off blocking for STDIN. The following code should be run like this perl script.pl send | perl script.pl #!/usr/bin/perl use strict; use warnings; use IO::File; if (defined $ARGV[0] and $ARGV[0] eq 'send') { STDOUT->autoflush(1); for my $i (1 .. 10) { print "sending $i\n"; sleep 3; } exit; } STDIN->blocking(0); my $timeout = 10; my $timer; while (1) { last if $timer++ > $timeout; local $_ = <STDIN>; if (defined) { print; $timer = 0; } sleep 1; print localtime() ."\n"; } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/