Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Forcing array context on a file handle

by toolic (Bishop)
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.

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1001551]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2018-04-22 20:26 GMT
Find Nodes?
    Voting Booth?