hl037_
hl037_

Reputation: 3907

Perl, how to read from stdin outside a loop?

There is something I don't understand :

say in is a file containing :

1
2
3

and foo.pl :

use strict;
<>;
print;
<>;
print;
<>;
print;

and then run :

perl foo.pl < in

Why this programm doesn't output anything ?

...While this one :

use strinct;
while(<>) {
    print;
}

output the whole file

Upvotes: 2

Views: 251

Answers (1)

TLP
TLP

Reputation: 67910

Because

while(<>) 

Is shorthand for

while($_ = <>) 

Which means the line is assigned to the default variable $_. Which is also used by print.

What you wrote:

<>;

Does not assign anything to $_. It is just a readline in void context, which means the value is discarded and not stored anywhere. Hence $_ is empty. If you use warnings, Perl will tell you what is going on.

Use of uninitialized value $_ in print

If you do the assignment manually it will work:

$_ = <>;

Note also that you do not have to redirect the file content, you can just supply the file name as an argument:

perl foo.pl in

Upvotes: 6

Related Questions