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 {
    my ($file, $ret_array) = @_;

    open (my $fh, "<", $file) or return undef;
    binmode($fh, ":encoding(UTF-8)");

    if ($ret_array) {
        my @ret;

        while (my $line = readline($fh)) {
            $line =~ s/[\r\n]*$//; # Remove CR/LF
            push(@ret, $line);
        }

        return @ret;
    } else {
        my $ret = '';
        while (my $line = readline($fh)) {
            $ret .= $line;
        }

        return $ret;
    }
}


Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 35.172.165.64
To prevent spam please submit by clicking the kitten: