1

I'm having some trouble with a JSON file that I'm opening from a weblink. I've adapted my code from what i used to open local kml files so the problem could be a different way perl handles json or opening online files...?

'$input{place}' comes from my html forms

$inputname = $input{place};
$sjson ="http://api.geonames.org/searchJSON?q=$inputname&maxRows=1&username=rsgs";
open INPUT, "<$sjson";
  $sjsoncont.=<INPUT>;  
  close INPUT;

When I test by printing $sjsoncont it is empty? Why?

4

2 回答 2

5

您不能简单地“打开”远程 URL。为此任务使用 LWP::UserAgent 或 LWP::Simple。例如:

use LWP::Simple;
my $sjsoncont = get "http://api.geonames.org/searchJSON?q=Berlin&maxRows=1&username=rsgs";

顺便说一句,如果你使用 open(),你应该总是检查返回值:

open my $INPUT, "<", $file or die "Can't open $file: $!";

(或use autodie

于 2013-07-11T19:34:49.863 回答
3

您可以使用以下方法执行此操作IO::All

use IO::All;
my $sjson < io->http("http://api.geonames.org/searchJSON?q=$inputname&maxRows=1&username=rsgs");
print $sjson;

要使用它,请安装IO::All::HTTP. 您可以通过cpan IO::All::HTTP从命令行运行来执行此操作。

看起来您没有使用警告和严格。要开发 perl,您确实必须这样做。您编写的每个脚本都应该以

use strict;
use warnings;

此外,如果您遇到不理解的 perl 错误,请添加以下错误:

use diagnostics;
于 2013-07-11T20:14:45.113 回答