Subject: | Documentation suggestion for article traditional slurp idiom that removes the need for the open call. |
Hello and thanks for File::Slurp,
In the excellent article:
extras/slurp_article.pod#Traditional_Slurping
The following is mentioned:
And this is a variant of that idiom that removes the need for the
open call:
my $text = do { local( @ARGV, $/ ) = $file ; <> } ;
I recently discovered that a more robust method is:
my $text = do { local( *ARGV, $/ ); @ARGV= $filename; <> };
http://www.perlmonks.org/?node_id=204922
Here is how to reproduce the behaviour I observed:
Define the environment variable TMPDIR to point to a NFS location.
use File::Temp 'tempdir';
my $temp_dir = tempdir( CLEANUP => 1 );
my $temp_file = File::Spec->catfile($temp_dir,'stig.tmp');
open my $OUT,'>',$temp_file or die $!;
print ${OUT} 'hello';
close $OUT;
# orig
my $text = do { local( @ARGV, $/ ) = $temp_file ; <> } ;
# new
# my $text = do { local( *ARGV, $/ ); @ARGV = $temp_file ; <> } ;
print "\$ARGV='$ARGV'\n";
print $text;
The original line produces:
$ARGV='<NFS test location used>/0QThNNoh0J/stig.tmp'
cannot remove directory for <NFS test location used>//0QThNNoh0J:
Directory not empty at <redacted>perl-5.12.1/lib/5.12.1/File/Temp.pm
line 902
hello
The new line produces:
Use of uninitialized value $ARGV in concatenation (.) or string at
idiom.pl line 18.
$ARGV=''
hello
and manages to remove the directory. While I'm not yet sure why tempdir
( CLEANUP => 1 ) fails in this way when on a NFS mount, I observed that
by localizing *ARGV the undesirable behaviour went away.
Just thought it worth mentioning the potential problem with this idiom
in the article. More details in the following nodes:
http://www.perlmonks.org/?node_id=204922
http://www.perlmonks.org/?node_id=204937
Cheers,
Peter (Stig) Edwards