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;
if ($_[1]) { # Line mode
return my @lines = readline($fh);
} else { # String mode
local $/ = undef; # Input rec separator (slurp)
return my $ret = readline($fh);
}
}