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?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.