为什么Perl的JSON模块不能读取或写入文件?

Dav*_*d B 3 perl json

我错过了什么,或JSON缺少write_to_file()read_from_file()子程序?

显然,我可以很容易地实现它们,但是因为它们看起来很方便,我想它们怎么可能不存在.

jon*_*oni 8

是的,它缺少write_to_file()read_from_file()功能,因为通常,您不会将JSON存储在文件中,而只是将其用于将数据发送回Web客户端.你必须自己实现它,正如你说的那样,没那么多.


小智 6

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 一些解释会很好. (3认同)