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

I am attempting to create a loop that will perform a function every $interval seconds. When I attempt to use the sleep function, the first line of the loop that I have create isn't executed. Without further ado, the code loop:
#!/usr/bin/perl -w my $interval=5; LOOP: { print STDOUT "test"; #used STDOUT here, just to be sure sleep ($interval); redo LOOP; }
Different variations of for(;;) while(), etc have also been tried with no success.

Replies are listed 'Best First'.
Re: Death of sleep?
by clintp (Curate) on Aug 08, 2001 at 18:13 UTC
    You are suffering from buffering. Try: $|=1 near the beginning of your program, or pick a file descriptor like STDERR that doesn't have this problem. More information in the FAQ...
Re: Death of sleep?
by trantor (Chaplain) on Aug 08, 2001 at 18:16 UTC
    STDOUT is buffered, this means that no actual output will be written until the buffer is full or there's a newline. If you print "test\n"; or if you set the $| variable to nonzero (e.g. with $|++; or with $| = 1;), you'll get what you want. Setting $| to a nonzero value disables buffering. Technically, it flushes it every time you write (to STDOUT, in your case).

    May I also suggest you to rework your simple loop? I know it's just a test, but it looks a bit weird: there's no need for redo and labels in this simple case, so I'd suggest you to use the variations you mentioned in your post.

    Happy learning!

    -- TMTOWTDI

Re: Death of sleep?
by Zaxo (Archbishop) on Aug 08, 2001 at 18:15 UTC

    Your code works if you set $|=1; before LOOP. That autoflushes the prints rather than waiting till STDOUT is closed ( too late then ;-).

    After Compline,
    Zaxo

Re: Death of sleep?
by John M. Dlugosz (Monsignor) on Aug 08, 2001 at 18:16 UTC
    Add the line $|=1; to the top of your script, “to make your pipes piping hot!”.

    The print is being executed, but the buffer isn't flushed.

    —John