1

I have encountered a problem in Perl. To test if the STDIN file handler has something to read immediately, I would like to program like this.

while(1)
{
     my ($l);
     if (TestCanRead(STDIN))
     {
         $l = <STDIN>;
         HandleRead($l);
     }
     else
     {
         HandleNotRead();
     }
}

or

 while(1)
 {
     my ($l);
     $l = ReadImmediate(STDIN);
     if (defined($l))
     {
         HandleRead($l);
     }
     else
     {
          HandleNotRead();
     }

 }

Can somebody tell me how to write the function ReadImmediate or TestCanRead on a Windows system? Thank you.

Daniel Standage
  • 8,136
  • 19
  • 69
  • 116

1 Answers1

2

Unfortunately, I don't have a Windows environment to test on, but Perl makes claims of portability. So lets assume the Unix solution works.

You want select or a wrapper around it. I usually use IO::Select, which looks like this:

use IO::File;
use IO::Select;

my $select = IO::Select->new( \*STDIN );

while (1) {
    if (my @ready_FHs = $select->can_read(0)) {
        foreach my $FH (@ready_FHs) {
            say $FH->getline();
        }
    } else {
        say "Nothing to do; napping";
        sleep 1;
    }
}
darch
  • 4,200
  • 1
  • 20
  • 23