){ print ...">

So what does <FILE> do?

So, I have used <FILE> many times. A simple example:

 open (FILE, '<', "someFile.txt"); while (my $line = <FILE>){ print $line; } 

So, I thought that using <FILE> would take part of the file at a time (line specifically) and use it, and when it was called again, it would go to the next line. And indeed, whenever I set <FILE> to a scalar, this is exactly what it would do. But when I told the computer a line like this:

 print <FILE>; 

he printed the whole file, new lines and all. So my question is: what does the computer think when it passes <FILE> , exactly?

+6
source share
3 answers

The diamond <> operator used to read from a file is actually a built-in readline function.

From perldoc -f readline

Reads from the file descriptor whose type glob is contained in EXPR (or from * ARGV if EXPR is not provided). In a scalar context, each call reads and returns the next line until the end of the file is reached, after which the next call returns undef. In the context of the list, it is read until the end of the file is reached and the list of lines is returned.

If you want to check a specific 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 
+12
source

It depends on whether it is used in a scalar context or in a list context.

In a scalar context: my $line = <file> it reads one line on a tie.
In the context of the list: my @lines = <FILE> it reads the entire file.

When you say print <FILE>; list context.

+7
source

The behavior is different depending on the context in which it is evaluated:

 my $scalar = <FILE>; # Read one line from FILE into $scalar my @array = <FILE>; # Read all lines from FILE into @array 

As print accepts a list argument, <FILE> is evaluated in the context of the list and behaves differently.

+2
source

Source: https://habr.com/ru/post/970627/


All Articles