ないテキストファイルの構造が何であるか、それがどのように一貫してくださいです。私はすべてのエントリーは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