That's because you haven't turned autoflush on for that STDOUT pipe. Please read the following documentation which I'll excerpt here:
http://perldoc.perl.org/perlvar.html $|
If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel. Default is 0 (regardless of whether the channel is really buffered by the system or not; $| tells you only whether you've asked Perl explicitly to flush after each write). STDOUT will typically be line buffered if output is to the terminal and block buffered otherwise. Setting this variable is useful primarily when you are outputting to a pipe or socket, such as when you are running a Perl program under rsh and want to see the output as it's happening. This has no effect on input buffering. See getc for that. (Mnemonic: when you want your pipes to be piping hot.)
Therefore to get your code to print out after each print statement, instead of each return character, simply add the following line:
-
#!/usr/bin/perl
-
use strict;
- local $| = 1;
-
my $val = 4;
-
for (my $i=0; $i<=$val; $i++) {
-
print "$i ";
-
sleep(1);
-
}
-
Also, you'll notice that I added the line "use strict;" do your program and scoped your two variables. This is a very good habit to get in, and it will save you a lot of grief in the future so I recommend that you ALWAYS do this.
http://perldoc.perl.org/strict.html
Finally, if you want to know more about buffering from a file perspective, you read the faq on files. The first question speaks directly to your issue:
http://perldoc.perl.org/perlfaq5.html
1) How do I flush/unbuffer an output filehandle? Why must I do this?