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

#!/usr/bin/perl -w use strict; my $str = "Hello!"; chomp($str); foreach (split // ,$str) { print $_,"\n"; sleep 1; }

gives this output with sleep one second for every character!:

H e l l o !

What I would like is about the same code, but with this output instead:

H e l l o !
This includes sleep one second between every character as in first code example above. This works fine, but the thing is; is it possible to get the output one character for every second and all on the same line? I have tried with /t instead of newline but that just gives me
H e l l o
in a bunch when code exits. So to be absolutely clear. I want output like this all on the same line:
h (sleep) e (sleep) l (sleep) l (sleep) o (sleep) !(sleep)

Replies are listed 'Best First'.
Re: split sleep question
by zwon (Abbot) on May 01, 2009 at 13:19 UTC

    It's easy, you should turn on autoflush on STDOUT

    use strict; use warnings; use IO::Handle; autoflush STDOUT 1; my $str = "Hello!"; chomp($str); foreach ( split //, $str ) { print $_, " "; sleep 1; } print "\n";

    Update: or use $|=1 as proposed by gwadej, in case of SDTOUT that perhaps better solution.

Re: split sleep question
by gwadej (Chaplain) on May 01, 2009 at 13:19 UTC

    You need to turn off buffering on STDOUT with $|=1 before the loop.

    G. Wade
Re: split sleep question
by marto (Cardinal) on May 01, 2009 at 13:28 UTC

    Adding $| = 1; (see Suffering from buffering) and replacing your \n with a space:

    #!/usr/bin/perl use strict; use warnings; $| = 1; my $str = "Hello!"; foreach ( split // , $str ){ print "$_ "; #note the space sleep 1; } print "\n";

    Will do what I think you want.

    Martin

      Thank You very much for Your fast replies! Both examples worked like a charm!