Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Re: Perl Idioms Explained - my $string = do { local $/; <FILEHANDLE> };

by antirice (Priest)
on Aug 29, 2003 at 20:31 UTC ( [id://287827]=note: print w/replies, xml ) Need Help??


in reply to Re: Perl Idioms Explained - my $string = do { local $/; <FILEHANDLE> };
in thread Perl Idioms Explained - my $string = do { local $/; <FILEHANDLE> };

A couple of things. First and foremost, don't you think that ought to be:

my $slurp = join $/, <FH>;

Otherwise you can't really distinguish between lines. Next, you're having perl read the file in, split the file on $/, and then rejoin everything and you end up with a string that was exactly what it was before the split. If you just localize $/ and then read the file in, you're done. Of course, I have some nice benchmarks that show the local $/ method to be a little under 5 times faster. As with any other benchmarks, YMMV.

#!/usr/bin/perl -w use Benchmark qw(cmpthese); # file.txt is about 2200 lines each between 5 and 50 chars long open FH, "file.txt" or die $!; sub scalarcon { seek(FH,0,0); local $/; <FH>; } sub listjoin { seek(FH,0,0); join '',<FH>; } cmpthese(-5,{scalarcon=>\&scalarcon,listjoin=>\&listjoin}); __DATA__ Benchmark: running listjoin, scalarcon for at least 5 CPU seconds... listjoin: 5 wallclock secs ( 5.25 usr + 0.12 sys = 5.38 CPU) @ 30 +.70/s (n=165) scalarcon: 6 wallclock secs ( 1.95 usr + 3.36 sys = 5.30 CPU) @ 15 +3.26/s (n=813) Rate listjoin scalarcon listjoin 30.7/s -- -80% scalarcon 153/s 399% --

Update: As chromatic has pointed out, I'm a twit.

Hope this helps.

antirice    
The first rule of Perl club is - use Perl
The
ith rule of Perl club is - follow rule i - 1 for i > 1

Replies are listed 'Best First'.
Re: Re: Re: Perl Idioms Explained - my $string = do { local $/; <FILEHANDLE> };
by chromatic (Archbishop) on Sep 02, 2003 at 21:25 UTC

    Your first suggestion would seem to double the input record separator. Did you test it? Do you somehow have autochomp enabled?

    #!/usr/bin/perl -w use strict; my $line = join $/, <DATA>; print "<<$line>>\n"; __DATA__ one two tie my shoe

Log In?
Username:
Password:

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

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

    No recent polls found