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

I have this loop:

while(<>){ ..... ..... if ($hour==0){ $var=0;} # it does not happend untill we have input from keyboard ..... ..... }

it waits untill keyboard in, and "if statment" wont do his job at the specfied time. now i want a loop that if i have keyboard in do loop 1 and if we dont have input from keyboard do loop 2
how can i do it

Edited by davido to touch up formatting to match original author intent. Please use html formatting tags.

Replies are listed 'Best First'.
Re: input problem
by edan (Curate) on Dec 19, 2004 at 09:21 UTC

    I think you mean that you want to loop "non-blocking", meaning that you want to continue processing even if there is no user input. To do that, one usually uses 4-arg select, or the OO-wrapper interface IO::Select. Here's a trivial example to get you started.

    use IO::Select; # loop every 1 second my $timeout = 1; my $s = IO::Select->new(); $s->add(\*STDIN); while ( 1 ) { if ( my @ready = $s->can_read($timeout) ) { # we got input for my $fh ( @ready ) { my $input = <$fh>; print "got: $input"; } } else { # no input } # just to show that we're looping print scalar localtime; }

    Update: I just remembered what select says about mixing buffered reading and "select", so even though the above code works, you might want to substitute the read via <$fh> with:

    my $input; sysread( $fh, $input, 1024);
    --
    edan

      Just to note, this won't work on win32.

      (To make it work, you'd probably need something like Win32::Console or Term::ReadKey that can read in a nonblocking way from stdin, something like getline(0))
Re: input problem
by ysth (Canon) on Dec 19, 2004 at 08:23 UTC
    I'm not clear on what you are looking for. Are you saying that input may come from the keyboard or may come from a file? Or you want to test if there is data ready to read from the keyboard?