Reputation: 388
So, I've used <FILE>
a large number of times. A simple example would be:
open (FILE, '<', "someFile.txt");
while (my $line = <FILE>){
print $line;
}
So, I had thought that using <FILE>
would take a a part of a file at a time (a line specifically) and use it, and when it was called on again, it would go to the next line. And indeed, whenever I set <FILE>
to a scalar, that's exactly what it would do. But, when I told the computer a line like this one:
print <FILE>;
it printed the entire file, newlines and all. So my question is, what does the computer think when it's passed <FILE>
, exactly?
Upvotes: 6
Views: 207
Reputation: 50657
Diamond operator <>
used to read from file is actually built-in readline
function.
From perldoc -f readline
Reads from the filehandle whose typeglob is contained in EXPR (or from *ARGV if EXPR is not provided). In scalar context, each call reads and returns the next line until end-of-file is reached, whereupon the subsequent call returns undef. In list context, reads until end-of-file is reached and returns a list of lines.
If you would like to check particular context in perl,
sub context { return wantarray ? "LIST" : "SCALAR" }
print my $line = context(), "\n";
print my @array = context(), "\n";
print context(), "\n";
output
SCALAR
LIST
LIST
Upvotes: 12
Reputation: 7912
The behaviour is different depending on what context it is being evaluated in:
my $scalar = <FILE>; # Read one line from FILE into $scalar
my @array = <FILE>; # Read all lines from FILE into @array
As print
takes a list argument, <FILE>
is evaluated in list context and behaves in the latter way.
Upvotes: 2
Reputation: 91498
It depends if it's used in a scalar context or a list context.
In scalar context: my $line = <file>
it reads one line at a tie.
In list context: my @lines = <FILE>
it reads the whole file.
When you say print <FILE>;
it's list context.
Upvotes: 7