Perlfunc: file_put_contents()

PHP has a really handy function called file_put_contents() that simplifies writing to a file. I did a quick Perl version of that function for my scripts.

sub file_put_contents {
    my ($file, $str) = @_;

    open (my $fh, ">", $file) or return undef;
    print $fh $str or return 0;
    close $fh;

    return length($str);
}

I also implemented a quick version of file_get_contents():

sub file_get_contents {
    open (my $fh, "<", $_[0]) or return undef;
    my $ret_array_ref = $_[1];

    my $ret;
    if ($ret_array_ref) {
        @$ret = readline($fh);
    } else {
        local $/ = undef; # Input rec separator (slurp)
        $ret  = readline($fh);
    }

    return $ret;
}
Leave A Reply
All content licensed under the Creative Commons License