正如其他人已经说过的那样,使用库来完成这项任务会更好(请参阅下面的代码示例)。如果你像 flesk 那样做,你必须确保,lat
总是在lon
. 这可能更健壮一点,但请注意,我将数据拆分为无效JSON
字符串的块:
#!/usr/bin/env perl
use strict;
use warnings;
# split in (invalid) object parts
my @chunks = split /},/ => <DATA>;
# iterate over chunks
for (@chunks) {
# extract latitude/longitude
my $lon = /"lon":([^,]+)/ ? $1 : 'UNKNOWN';
my $lat = /"lat":([^,]+)/ ? $1 : 'UNKNOWN';
# print data
print "lon: $lon, lat: $lat\n";
}
__DATA__
[{"lon":77.594376,"lat":12.971606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.604376,"lat":12.980606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.674376,"lat":12.981606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.684376,"lat":12.982606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.744376,"lat":12.983606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.784376,"lat":12.990606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.804376,"lat":12.991606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.824376,"lat":12.995606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.874376,"lat":12.997606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.894376,"lat":12.999606,"bfg":18000,"xyz":null,"jky":null}]
输出:
lon: 77.594376, lat: 12.971606
lon: 77.604376, lat: 12.980606
lon: 77.674376, lat: 12.981606
lon: 77.684376, lat: 12.982606
lon: 77.744376, lat: 12.983606
lon: 77.784376, lat: 12.990606
lon: 77.804376, lat: 12.991606
lon: 77.824376, lat: 12.995606
lon: 77.874376, lat: 12.997606
lon: 77.894376, lat: 12.999606
一个更好、更简单的解决方案将只使用JSON库:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON 'decode_json';
# decode input
my $objects = decode_json <DATA>;
# iterate over objects and print data
printf "lon: %f, lat: %f\n", $_->{lon}, $_->{lat} for @$objects;
__DATA__
[{"lon":77.594376,"lat":12.971606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.604376,"lat":12.980606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.674376,"lat":12.981606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.684376,"lat":12.982606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.744376,"lat":12.983606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.784376,"lat":12.990606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.804376,"lat":12.991606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.824376,"lat":12.995606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.874376,"lat":12.997606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.894376,"lat":12.999606,"bfg":18000,"xyz":null,"jky":null}]
输出:同上。
所以,除非您完全知道自己在做什么,否则请不要手动操作!:)