Why does "while (<>) { $x .= $_; } print $x . "\n";" print all input lines?

W

Wolfgang

Being familiar with other programming languages, I had assumed that
only the very last input line would be printed by the code below. I
was thinking that because the print statement is outside the 'while'
loop.

$x = "";
while (<>) {
$x .= $_;
}
print $x . "\n";

Why does this code print all input lines?

Thanks,
Wolfgang


while (<>) { $x .= $_; } print $x . "\n";
 
P

Paul Lalli

Being familiar with other programming languages, I had assumed that
only the very last input line would be printed by the code below. I
was thinking that because the print statement is outside the 'while'
loop.

$x = "";
while (<>) {
$x .= $_;
}
print $x . "\n";

Why does this code print all input lines?

Thanks,
Wolfgang


while (<>) { $x .= $_; } print $x . "\n";

Because you're concatenating $x with the next line from the input file
each time through the loop. .= is the 'concatenate and assign' operator.
It takes whatever was previously in $x, and adds $_ onto the end of it.
Therefore, when you print $x at the end, it contains all lines from the
file.

Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top