不知道你的文本文件的结构是什么,以及如何一致的是。我认为每个条目都是5行,每个条目的顺序相同。如果是这种情况,可能有一种方法是一次读取5行文本文件,将每行分配给相应的散列键,然后将该散列值存储在一个数组中,稍后我们可以使用该数组作为JSON结构体。也许一个更优雅的方式做到这一点,但对于这样的事情:
#!/usr/bin/perl
use strict;
use warnings;
use autodie;
use JSON;
my $input_file = shift;
my @results;
open(my $fh, "<", $input_file);
# Read the text file 5 lines at a time, and store each line in the hash data with the desired keys.
while ((my @lines) = map { scalar(<$fh>) or() } 0..4) {
my %data = ('beername' => $lines[0],
'location' => $lines[1],
'ABV' => $lines[2],
'IBU' => $lines[3],
'Rating' => $lines[4],
);
# Store these hash refs in an array that we'll later convert to JSON.
push(@results, \%data);
}
# Write results to file.
open(my $json_out, ">", 'beers.json');
print {$json_out} encode_json(\@results);
这将导致“beers.json”文件,该文件将具有以下结构:
$ json_xs <beers.json
[
{
"ABV" : "5.2\n",
"IBU" : "13.65\n",
"location" : "Lawrence, Kansas, USA\n",
"Rating" : "Rating - 0.00\n",
"beername" : "23rd Street Wave the Wheat Ale\n"
},
{
"ABV" : "5.2\n",
"IBU" : "Unknown\n",
"location" : "Carbondale, Pennsylvania, USA\n",
"Rating" : "Rating - 0.00\n",
"beername" : "3 Guys & A Beerââ¬â¢d Wheat the People\n"
},
{
"location" : "Lake Orion, Michigan, USA\n",
"Rating" : "Rating - 0.00\n",
"beername" : "51 North Paint Creek Wheat\n",
"IBU" : "Unknown\n",
"ABV" : "4.8\n"
}
]
就像我说的,可能不够高雅,完全依赖于每个啤酒的文件长度为5行,每个啤酒的元数据每次都是相同的顺序。但是,如果没有别的办法,这可能是一个很好的起点?
使用模块[JSON](http://search.cpan.org/~ishigaki/JSON-2.94/lib/JSON.pm) – zdim
“失败”是什么意思?当你运行你的程序时会发生什么?你预期会发生什么?发表一个https://stackoverflow.com/help/mcve – Robert
我很困惑...你要求帮助存储数据,但是你显示一个文本文件而不是数据结构?! – ikegami