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

Re: Reading files in scalar context with <> operator

by BaldPenguin (Friar)
on Aug 06, 2005 at 14:08 UTC ( [id://481527]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to Reading files in scalar context with <> operator

Unfortunately not all functions will send back the contectula meaning you think it implied. Different list returning functions will return different things when returning scalars. localtime will return a join of it's array; readline ( and likewise <> ) will return the 'next' value in the series ( mainly I think, because it's designed to be iterative ); Others may return the array and default to the scalar value as you had thought about the <> statement

I believe the important thing would be to not make assumptions. Once you get to know which returns which, you might be tempted to make accomodate each. I myself would stick to what I know would work, in this case return an array, then use scalar to get the count
.... my @lines = <$fh>; my $count = scalar @lines; ....
That also tends to allow others reading your code to understand your code, especially if they still do not know the ins and outs of contextual returns.

As far as reading the file, slurp works well and I won't dispute it's usefulness, but I am still old school.
# Unstested my strict; my warnings; my $content = ''; my $filename = 'myfile.txt'; { local $\; open $fh, '<', $filename or die "Cannot open $filename: $!\n"; $content = <$fh>; close $fh; } print $content;
Here we localize the input record seperator, or enable 'slurp' mode, and the call using <> will pull in the whole file.

Don
WHITEPAGES.COM | INC
Everything I've learned in life can be summed up in a small perl script!

Replies are listed 'Best First'.
Re^2: Reading files in scalar context with <> operator
by senõr_biggles (Novice) on Aug 06, 2005 at 15:19 UTC
    OK. I see. Thank you very much for your answers.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://481527]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.