我正在使用 read_file
模块中的
File::Slurp
子模块和 decode_json
模块中的
JSON
子模块来轻松读取文件内容以进行 JSON 解码。但是,我发现当我的文件包含换行符时,我无法直接将 read_file
的返回值传递给 decode_json
,因为我收到了有关无效 JSON 的错误。相反,我必须在传递 read_file
的返回值之前将其存储到变量中。
我对 Perl 还很陌生(根据系统使用 v5.30 或 v5.38),并且来自 JS 和 Python 等语言,这让我感到惊讶;为什么需要这个中间变量赋值?并不是说这不是一个足够简单的解决方法,只是为了满足我的好奇心。
示例:
use v5.38;
use warnings;
use strict;
use File::Slurp qw( read_file );
use JSON qw( decode_json );
my $contents = read_file('test.json');
my $decoded = decode_json($contents);
say "Decoded contents";
my $chained_decoded = decode_json( read_file('test.json') );
say "Decoded chained contents";
文件
test.json
旁边包含内容:
[{ "a": "b" }, { "b": "c" }]
这不会导致任何错误,并且两个日志都会显示。
但是,内容:
[
{ "a": "b" },
{ "b": "c" }
]
我看到了第一个日志,但随后抛出了错误
, or ] expected while parsing array, at character offset 2 (before "(end of string)") at test.pl line 12.
read_file
被记录为上下文相关:在标量上下文中,它将文件的全部内容作为一个字符串返回。在列表上下文中,它返回行列表。
函数调用的参数列表是一个列表上下文,但
decode_json
不需要行列表,它需要第一个参数中的整个文件并忽略其余部分。
您可以通过编写
decode_json(scalar read_file('test.json'))
来强制标量上下文。