2008年8月21日星期四

http://www.perl.com/pub/a/2003/11/21/slurp.html
Both of those slurps used localized filehandles to be compatible with 5.005. Here they are with 5.6.0 lexical autovivified handles:
{
local( $/ ) ;
open( my $fh, $file ) or die "sudden flaming death\n"
$text = <$fh>
}
open( my $fh, $file ) or die "sudden flaming death\n"
my $text = do { local( $/ ) ; <$fh> } ;
And this is a variant of that idiom that removes the need for the open call:
my $text = do { local( @ARGV, $/ ) = $file ; <> } ;
The filename in $file is assigned to a localized @ARGV and the null filehandle is used which reads the data from the files in @ARGV.
Instead of assigning to a scalar, all the above slurps can assign to an array and it will get the file but split into lines (using $/ as the end of line marker).
There is one common variant of those slurps which is very slow and not good code. You see it around, and it is almost always cargo cult code:

没有评论: