Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Forcing array context on a file handle

by toolic (Chancellor)
on Oct 30, 2012 at 20:56 UTC ( #1001551=note: print w/ replies, xml ) Need Help??


in reply to Forcing array context on a file handle

"$lines = @{[ (<$file>) ]}".The problem is that the former doesn't work, and the latter gives $lines = 1.
Your 2nd example gives me the correct number of lines (not 1):
use warnings; use strict; open my $file, '<', $0; my $lines = @{[ (<$file>) ]}; print "$lines\n";

The output for me is 5.


Comment on Re: Forcing array context on a file handle
Select or Download Code
Re^2: Forcing array context on a file handle
by tobyink (Abbot) on Oct 30, 2012 at 21:07 UTC

    Yes, I was a bit surprised by the assertion that this didn't work. I can only suppose the OP forgot the angled brackets when testing.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re^2: Forcing array context on a file handle
by ronmrdechai (Novice) on Oct 30, 2012 at 21:33 UTC

    That's odd. It works for me too, but it doesn't work in my larger program (I have all the brackets, and in the right order). I have some extra stuff going around with the file handle, so maybe that's what's causing trouble.

    I ended up going with BowserUK's solution, which is slightly shorter than the method I was using before.

      After you read a file you have to rewind it with seek if you want to read it again from the beginning. Here is how to set the filehandle back to the beginning of the file.

      seek $fh, 0, 0;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1001551]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2014-10-01 01:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (386 votes), past polls