Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please, help me to understand the snippet from the "Programming Perl" book

I read the "Programming Perl" by By Tom Christiansen, brian d foy, Larry Wall, Jon Orwant. There is the following text which I failed to understand (the exact places which I do not understand are marked with bold):

What you really want to know is which operators supply which context to their operands. As it happens, you can easily tell which ones supply list context because they all have LIST in their syntactic descriptions. Everything else supplies scalar context. Generally, it’s quite intuitive. If necessary, you can force scalar context onto an argument in the middle of a LIST by using the scalar pseudofunction. Perl provides no way to force list context in context, because anywhere you would want list context it’s already provided by the LIST of some controlling function.

For convenience I would like to formulate the following questions:

  1. What does it mean LIST in the snippet?

  2. What is syntactic description? (seems to be a some sort of documentation)

  3. What does it mean the next text:

you can force scalar context onto an argument in the middle of a LIST

like image 600
Dmitry Koroliov Avatar asked Dec 27 '22 21:12

Dmitry Koroliov


1 Answers

It's quite simple, like the text says. Take a look at perldoc -f print for example:

print FILEHANDLE LIST
print FILEHANDLE
print LIST

Like it says right there, print takes LIST arguments, meaning anything posted after print is in list context. It is the same for any function where the argument(s) are denoted as LIST.

With the scalar function, you can override this list context, so that your argument is not evaluated in list context. For example, a file handle readline statement such as:

my $line = <$fh>;

Is evaluated in scalar context, because $line is a scalar. This means only one line is read and put into the variable. However, if you were to do:

print <$fh>;

The readline is in list context, which means all remaining lines in the file will be read. You can override this by putting the readline statement in scalar context:

print scalar <$fh>;

And then you will just read one line. To be more precise, you can enforce scalar context in the middle of a list:

print @list, scalar <$fh>, @list2;

Which presumably is what is referred to in that quote of yours.

like image 191
TLP Avatar answered May 22 '23 09:05

TLP