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 $file = shift();
    if (!-r $file) { return ''; } # Make sure the file is readable

    my $ret = '';

    open(INPUT, "<", $file);
    while (<INPUT>) {
        $ret .= $_;
    }
    close INPUT;

    if (wantarray) {
        return split(/\n/,$ret);
    } else {
        return $ret;
    }
}
Leave A Reply - 1 Reply
Replies
Diego 2010-09-25 05:15am - dvadell@clustering.com.ar - Logged IP: 190.247.100.137

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

All content licensed under the Creative Commons License