Why does STDIN work in a list context?

Depending on the context, we get either a scalar or an array. Okay bye. But in the following:

print reverse <STDIN>; 

Why am I getting a list context? I mean reverse according to doc - this is either a list or a scalar context. So print .

Prints a line or list of lines. Returns true if successful.

So, STDIN . So, why does STDIN retrieve rows before EOF and not just collect the first row?

+4
source share
3 answers

It seems you are combining two independent things:

  • The operator is evaluated in a list, scalar or empty context.
  • The operator decides in which context its operands are evaluated.

Reverse operands are always evaluated in the context of the list.

 reverse LIST 

So, <STDIN> will be evaluated in the context of the list.


Like all operators that can return something other than a scalar, reverse behaves differently in a scalar context and in a list context.

The print operands are always evaluated in the context of the list.

 print LIST 

So reverse will be evaluated in the context of the list. This means that he will change the order of his operands. It will not reverse the character order of each operand, and it will not concatenate the list.

+7
source

In fact, print always prints a list of lines. You can pass it a scalar, but it will behave as if it were one of them.

So, in this case, reverse knows that it is called in the context of the list and thus changes its list argument.

+3
source

print reverse <STDIN>; essentially coincides with:

 @lines = <STDIN>; @reversed_lines = reverse @lines; print @reversed_lines; 

Saying $line = <STDIN>; will read one line from STDIN, whereas @line = <STDIN>; reads a list from STDIN.

The print argument list is always the list context. The line context can be enforced using the concatenation operator: print reverse <STDIN> . ""; print reverse <STDIN> . ""; will read a line, not a list.

+2
source

All Articles