0

Hi, suppose I have a file named first.txt from which I want to read. Suppose the text file looks like this:

I like you.
I feel your soul.

Now if I use this:

open cool, "< first.txt";
print <cool>;

the entire file content is printed, but if I use this:

open cool, "< first.txt";
print length(<cool>);

only 12 is printed (the length of the first line only, including newline), whereas it should be 27 (the length of the entire file content), because <cool> contains the entire file content, right, otherwise how could it have printed the entire content? So why is this happening?

2
Contributors
1
Reply
4
Views
5 Years
Discussion Span
Last Post by d5e5
1

Every Perl expression is in one of two `contexts', either `list context' or `scalar context', depending on whether it is expected to produce a list or a scalar. Many expressions have quite different behaviors in list context than they do in scalar context.

http://perl.plover.com/context.html
The print command expects a list as its argument so the filehandle following print is called in a list context. When called in a list context a filehandle reads all the remaining lines in the file.

The length command puts its argument in a scalar context. When called in a scalar context a filehandle reads only one line from the file.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.