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

Re^5: $_ and filehandles

by Ven'Tatsu (Deacon)
on Aug 29, 2005 at 02:30 UTC ( [id://487326]=note: print w/replies, xml ) Need Help??


in reply to Re^4: $_ and filehandles
in thread $_ and filehandles

I think your misunder standing was that you belived that the items on the right hand side of the = coresponded with the items on the left hand side. In Perl if the left hand side looks like a list or an array (any time there is an array or parentheses) all arguments on the right hand side are flatend into a single list, and asigned to the left hand side from left to right with a scalar (or undef) consuming one item, and the first array or hash consuming all remaining items.

my (undef, $salt, @post, @time) = (<FILE>, <FILE>, (), ());

So on this line your using <FILE> in array context, the entire contents of the file will be read in and returned as a list. Then the first line is discarded, the second line placed in $salt and the rest of the lines in @post, because @post consumes all the lines there is no data to place in @time so @time is left empty. After that point there is no more data to read so your while loop's conditional evaluates to false on the first test and the split is never executed. The print statment displays the 3 lines contained in @post as would be expected.

A solution would be to not give the first 2 uses of <FILE> array context, either by directly asigning to a scalar, or by forcing scalar context with the scalar() function.

<FILE>; #discard a line (one line is read in void context) my $salt = <FILE>; #provide scalar context so only one line is read my (@post, @time); ($post[$#post + 1], $time[$#time + 1]) = split(/;/) while (<FILE>); print "@post\n@time\n";
my (undef, $salt, @post, @time) = (scalar(<FILE>), scalar(<FILE>)); #f +orce scalar context. ($post[$#post + 1], $time[$#time + 1]) = split(/;/) while (<FILE>); print "@post\n@time\n";

I find the first better as long as you comment that you want to discard the line when <FILE> is on a line by it self.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-19 18:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found