How can I test STDIN without blocking in Perl?

前端 未结 2 1999
孤街浪徒
孤街浪徒 2021-02-19 19:05

I\'m writing my first Perl app -- an AOL Instant Messenger bot that talks to an Arduino microcontroller, which in turn controls a servo that will push the power button on our sy

2条回答
  •  醉梦人生
    2021-02-19 19:48

    The Perl built-in is select(), which is a pass-through to the select() system call, but for sane people I recommend IO::Select.

    Code sample:

    #!/usr/bin/perl
    
    use IO::Select;
    
    $s = IO::Select->new();
    $s->add(\*STDIN);
    
    while (++$i) {
      print "Hiya $i!\n";
      sleep(5);
      if ($s->can_read(.5)) {
        chomp($foo = );
        print "Got '$foo' from STDIN\n";
      }
    }
    

提交回复
热议问题