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, $data) = @_;

    open(my $fh, ">", $file) or return undef;
    binmode($fh, ":encoding(UTF-8)");
    print $fh $data;
    close($fh);

    return length($data);
}

I also implemented a quick version of file_get_contents():

sub file_get_contents {
    open(my $fh, "<", $_[0]) or return undef;
    binmode($fh, ":encoding(UTF-8)");

    my $array_mode = ($_[1]) || (!defined($_[1]) && wantarray);

    if ($array_mode) { # Line mode
        my @lines  = readline($fh);

        # Right trim all lines
        foreach my $line (@lines) { $line =~ s/[\r\n]+$//; }

        return @lines;
    } else { # String mode
        local $/       = undef; # Input rec separator (slurp)
        return my $ret = readline($fh);
    }
}
Leave A Reply
All content licensed under the Creative Commons License