devcoder
devcoder

Reputation: 1685

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%20s", $_;
}

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.

Upvotes: 2

Views: 291

Answers (1)

ysth
ysth

Reputation: 98398

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.

Upvotes: 1

Related Questions