954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Anomaly in file input handler

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 contains the entire file content, right, otherwise how could it have printed the entire content? So why is this happening?

Cupidvogel
Newbie Poster
22 posts since Sep 2011
Reputation Points: 10
Solved Threads: 0
 
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.

d5e5
Practically a Posting Shark
810 posts since Sep 2009
Reputation Points: 159
Solved Threads: 159
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: