我一直在使用Perl构建模拟器,我面临的一个问题是解析位于计算机中的
JSON文件.当我尝试从我的服务器中取出它们时,它们工作得很好……
method getContent(\@arrURLS) {
my %arrInfo;
my $resUserAgent = Mojo::UserAgent->new;
foreach my $strURL (@arrURLS) {
$resUserAgent->get($strURL => sub {
my($resUserAgent,$tx) = @_;
if ($tx->success) {
my $strName = basename($strURL,'.json');
my $arrData = $tx->res->body;
$arrInfo{$strName} = $arrData;
}
Mojo::IOLoop->stop;
});
Mojo::IOLoop->start;
}
return \%arrInfo;
}
我们假设@arrURLS是:
my @arrURLS = ("file:///C:/Users/Test/Desktop/JSONS/first.json","file:///C:/Users/Test/Desktop/JSONS/second.json");
以上网址是那些不起作用的网址,但如果我将其更改为:
my @arrURLS = ("http://127.0.0.1/test/json/first.json","http://127.0.0.1/test/json/second.json");
有用.
另外我想使用比Mojo :: UserAgent更好的东西,因为它看起来有点慢,当我使用Coro和LWP :: Simple时速度要快得多但不幸的是Coro在Perl 5.22中被破坏了……
解决方法
用户代理主要用于通过http下载文件.通常不期望它们处理文件系统URI.您自己需要
open和
read the file,或者使用像
File::Slurp这样的模块为您完成.
它可能看起来像这样.
use File::Slurp 'read_file';
method getContent(\@arrURLS) {
my %arrInfo;
my $resUserAgent = Mojo::UserAgent->new;
foreach my $strURL (@arrURLS) {
if (substr($strURL,4) eq 'file') {
$arrInfo{basename($strURL,'.json')} = read_file($strURL);
} else {
$resUserAgent->get($strURL => sub {
my($resUserAgent,$tx) = @_;
if ($tx->success) {
my $strName = basename($strURL,'.json');
my $arrData = $tx->res->body;
$arrInfo{$strName} = $arrData;
}
Mojo::IOLoop->stop;
});
Mojo::IOLoop->start;
}
}
return \%arrInfo;
}
