Perlfunc: pfile()
PHP has a handy function named file()
that will read the contents of a file into a variable. I wrote a quick Perl version of the same function.
sub pfile {
my $target = shift();
my $is_fh = defined(fileno($target));
my $ret;
# If we passed in a FH read everything from that
if ($is_fh) {
while (readline($target)) { $ret .= $_; }
# Else it's a file to be opened
} else {
open (my $fh, "<", $target) or return undef;
while (<$fh>) { $ret .= $_; }
}
if (wantarray) {
return split('\n',$ret);
}
return $ret;
}
Tags:
Leave A Reply
- 1 Reply
Replies
September 25th 2010 - Diego
Hi
Perl has a read_file() function. AFAIK you have to install an extra module, but it is as easy as running "cpan File::Slurp".
use File::Slurp;
my $file = read_file( $file );
Regards, -- Diego