Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

sleep in infinite loop

by my_nihilist (Sexton)
on Mar 13, 2008 at 14:30 UTC ( #673975=perlquestion: print w/replies, xml ) Need Help??
my_nihilist has asked for the wisdom of the Perl Monks concerning the following question:

why doesn't this work:
#!/usr/bin/perl use warnings; use strict; while (1) { sleep 5; print "interval"; }

Replies are listed 'Best First'.
Re: sleep in infinite loop
by olus (Curate) on Mar 13, 2008 at 14:37 UTC

    Flush the output:

    #!/usr/bin/perl use warnings; use strict; $| = 1; while (1) { sleep 5; print "interval"; }
      Ending the line will also force it to display immediately, so print "interval\n" will fix this. It's also probably what the OP actually meant to do, unless he wanted to see "intervalintervalinterval..." all the way across the screen.
      you are my GOD !!!! I've been trying to do this for two weeks.. Thanks mate.. By the way what does this "flush" thing do and how it helps in rectifying the problem?? Thanks Shamal
Re: sleep in infinite loop
by moritz (Cardinal) on Mar 13, 2008 at 14:39 UTC
    It works, but you don't see the output because the output is line buffered, and you don't print a newline.

    If you print "interval\n" instead it works as expected.

Re: sleep in infinite loop
by Narveson (Chaplain) on Mar 13, 2008 at 15:33 UTC

    For what it's worth, you can make your infinite loop condition accomplish something for you:

    while (sleep 5) { print "interval\n"; }
Re: sleep in infinite loop
by my_nihilist (Sexton) on Mar 13, 2008 at 14:44 UTC
    olus and moritz are both right. thanx. i presume that is why removing "sleep 5" produces a screenful all at once (i thought my eyes were just slow)
Re: sleep in infinite loop
by FunkyMonk (Canon) on Mar 13, 2008 at 23:56 UTC
    You can add $| = 1 to turn on autoflush, then you'll see each "interval" as you print them.

      But how to print it to a file? Even after printing it, the file is of zero byte.

        Based on the code that you provided, you're not doing anything with any files. Your print statement is only printing to STDOUT (i.e. your monitor).

        Assuming that you want to print to both your screen and the file, the modifications to your code below should work.

        #!/usr/bin/perl use warnings; use strict; my $file = "file.txt"; open(OF,">",$file) || die "Unable to open file '$file': $!\n"; while (1) { sleep 5; print "interval\n"; # prints to screen print OF "interval\n"; # prints to file } close(OF);

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://673975]
Approved by olus
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2017-06-25 02:30 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (564 votes). Check out past polls.