Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleep doesn't have any effect when iterating over a string to simulate typing

Tags:

perl

I want to make a script which will type string letters one by one

my $str = 'Test String';
my @spl = split '',$str;
for (@spl){
    print "$_";
    sleep(1);
}
print "\n";

sleep() doesn't do it's job! it makes me wait more than 1 second and im getting the full text immediately without any delay.

like image 531
Pythonizer Avatar asked Sep 02 '25 16:09

Pythonizer


2 Answers

In your loop, you are only outputting 2 items. There is also the fact that your output may be buffered and therefore the buffer may only be flushed and printed when the \n gets sent.

Try setting $| to a non-zero value which may disable the line buffering.

e.g

$| = 1; 
$|++; // alternative often seen

Alternatively, this does the same thing:

STDOUT->autoflush(1);    # Needs "use IO::Handle;" on older versions of Perl

Although probably not the issue here,sleep() is not a good way of waiting for a second, especially on older systems. As the manual states, there are reasons why sleep may take less than or more than 1 second.

like image 149
vogomatix Avatar answered Sep 05 '25 05:09

vogomatix


Put

use IO::Handle;
STDOUT->autoflush();

before printing, to disable output buffering (and thus waiting to fill buffer first).

like image 42
mpapec Avatar answered Sep 05 '25 04:09

mpapec