2 Replies - 10139 Views - Last Post: 23 January 2012 - 02:56 AM

#1 cupidvogel   User is offline

  • D.I.C Addict

Reputation: 31
  • View blog
  • Posts: 593
  • Joined: 25-November 10

Anomaly in file input handler

Posted 19 January 2012 - 11:41 PM

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

Quote

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?

Is This A Good Question/Topic? 0
  • +

Replies To: Anomaly in file input handler

#2 dsherohman   User is offline

  • Perl Parson
  • member icon

Reputation: 227
  • View blog
  • Posts: 654
  • Joined: 29-March 09

Re: Anomaly in file input handler

Posted 23 January 2012 - 02:41 AM

View Postcupidvogel, on 20 January 2012 - 07:41 AM, said:

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?


Many functions and operators in Perl are sensitive to context. When you use them in a different context, they produce different results.

View Postcupidvogel, on 20 January 2012 - 07:41 AM, said:

print <cool>;



The 'print' function can take a list of arguments (e.g., 'print $foo, $bar, $baz;'), so this places <cool> into list context. In list context, the <> operator returns the entire contents of the file, allowing you do do things like
my @entire_file_content = <cool>;


View Postcupidvogel, on 20 January 2012 - 07:41 AM, said:

print length(<cool>);



The 'length' function only takes a single argument, so this evaluates <cool> in scalar context. In scalar context, the <> operator returns one line at a time, allowing you to do things like
while (my $line = <cool>) {
  process_one_line($line);
}


Most people seem to find context one of the trickier concepts in Perl to grasp, but it's a very powerful tool once you get comfortable with it.
Was This Post Helpful? 1
  • +
  • -

#3 cupidvogel   User is offline

  • D.I.C Addict

Reputation: 31
  • View blog
  • Posts: 593
  • Joined: 25-November 10

Re: Anomaly in file input handler

Posted 23 January 2012 - 02:56 AM

Wow. That was cool. I was well-versed in Python, and I never imagined that any language will impress me after Python, given it's so succinct and comes with tons of features. But Perl did just that, it is awesome!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1