开发者

Code not printing last element of array when using using CTRL+Z to end the STDIN input

I seem to have run into a peculiar problem. Here is the code

#read a list of strings and print in 20-character column

print "Enter your strings:\n";
chomp(@list = <STDIN>);

foreach $_ (@list){
    printf "\n%20开发者_如何学运维s", $_;
}

The code doesn't print the last element of the array if I don't press enter before invoking end of file CTRL+Z on windows.

EDIT: Here's a sample output

Enter your strings:
a
v
b
                   a
                   v

here I pressed Ctrl-Z after entering b and before pressing enter, and it didn't print b. If I had pressed enter then Ctrl-Z, it would have printed b.


STDOUT is line-buffered when going to a terminal; data doesn't actually get shown until you add a newline. Try:

print "Enter your strings:\n";
chomp(@list = <STDIN>);
print "\n";
foreach $_ (@list){
    printf "%20s\n", $_;
}

or adding $| = 1; before the loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜