File::Slurp

slaniel | Uncategorized | Tuesday, July 4th, 2006

One more discovery in the gradual de-ghettoizing of my code: File::Slurp. I’ve written little functions like so before:

sub slurp { my $filename = shift; use FileHandle; my $fh = new FileHandle; $fh->open("<$filename") or ((warn "Could not open $filename for reading") and return "); return wantarray ? (<$fh>) : (join ", <$fh>); } 

but it looks like someone has taken the time to make a much better-performing version of the same thing. I always forget to look around for better approaches to my own quick hacks, but I’m pretty sure it’s more efficient overall to take the time to research beforehand.

(Likewise for something like

sub dumpStringToFile { my $string = shift; my $filename = shift; use FileHandle; my $fh = new FileHandle; open(">$filename") or ((warn "Could not open $filename for writing") and return "); print $fh $string; return 1; } 

)

Thanks to Perl Monks for pointing me to the library, and thanks to Adam Rosi-Kessel for pointing me to Perl Monks.

P.S.: If I’ve wanted to create a temporary file that’s guaranteed to not overwrite an existing file, I’ve been calling out to mktemp(1), but it looks like IO::File is a better way. This bit in particular seems cool:

newtmpfile

Creates an IO::File opened for read/write on a newly created temporary file. On systems where this is possible, the temporary file is anonymous (i.e. it is unlinked after creation, but held open). If the temporary file cannot be created or opened, the IO::File object is destroyed. Otherwise, it is returned to the caller.

P.S. (8 July 2006): It looks like File::Slurp is not internationalization-friendly: if it encounters a wide character, even while use IO => ":encoding(iso-8859-1)" is on, it dies. It could just be that I’m misunderstanding how Perl layers (or “Perl disciplines”) work, but I’m inclined to think not: using Unicode::String and then doing File::Slurp::writefile($filename, latin1($string) makes everything work copacetically.

1 Comment

  1. Thanks to Perl Monks for pointing me to the library, and thanks to Adam Rosi-Kessel for pointing me to Perl Monks.
    And who, pray tell, pointed you to Adam Rosi-Kessel?

    Comment by Adam Rosi-Kessel — January 1, 1970 @ 8:00 am

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.