开发者

Why does Perl's JSON module not read or write files?

开发者 https://www.devze.com 2023-01-22 07:55 出处:网络
Am I missing anything, or does JSON lacks a write_to_file() and read_from_file() s开发者_开发技巧ubroutines?

Am I missing anything, or does JSON lacks a write_to_file() and read_from_file() s开发者_开发技巧ubroutines?

Obviously, I can easily implement them, but as they seem so handy I wonder how can it be they are not there.


Yeah, it lacks a write_to_file() and read_from_file() function because usually, you don't store JSON in files but use it only to send data back to the web client. You've got to implement it by yourself, which, as you said correctly, isn't that much to do.


use JSON;

sub read_from_file {
my $json;
{
  local $/; #Enable 'slurp' mode
  open my $fh, "<", "data_in.json";
  $json = <$fh>;
  close $fh;
}
return decode_json($json);
}

sub write_to_file {
my $data  = shift;
open my $fh, ">", "data_out.json";
print $fh encode_json($data);
close $fh;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号