【发布时间】:2021-01-27 07:01:54
【问题描述】:
我想修改我的 Perl 脚本以使用 json_encode 函数输出变量列表,但我不确定如何。
这是我未修改的 Perl 脚本的输出:
Vicia_sativa = Vicia_sativa.png
Geranium_maculatum = Geranium_maculatum.png
Narcissus_pseudonarcissus = Narcissus_pseudonarcissus1.png Narcissus_pseudonarcissus2.png
Polygonum_persicaria = Polygonum_persicaria1.png Polygonum_persicaria2.png
Corylus_americana = Corylus_americana1.png Corylus_americana2.png
等号左边的变量是植物名称,等号右边的一个或多个文件名是植物照片。请注意,这些文件名没有用逗号分隔。
这是生成上述输出的 Perl 脚本:
#!/usr/bin/perl
use strict;
use warnings;
use English; ## use names rather than symbols for special variables
my $dir = '/Users/jdm/Desktop/xampp/htdocs/cnc/images/plants';
opendir my $dfh, $dir or die "Can't open $dir: $OS_ERROR";
my %genus_species; ## store matching entries in a hash
for my $file (readdir $dfh)
{
next unless $file =~ /.png$/; ## entry must have .png extension
my $genus = $file =~ s/\d*\.png$//r;
push(@{$genus_species{$genus}}, $file); ## push to array,the @{} is to cast the single entry to a reference to an list
}
for my $genus (keys %genus_species)
{
print "$genus = ";
print "$_ " for sort @{$genus_species{$genus}}; # sort and loop though entries in list reference
print "\n";
}
请告知如何在 JSON 数组中输出这些变量。谢谢。
更新...这是修订后的脚本,其中包含每个论坛成员的建议更改:
#!/usr/bin/perl
use strict;
use warnings;
use JSON::PP;
use English; ## use names rather than symbols for special variables
my $dir = '/Users/jdm/Desktop/xampp/htdocs/cnc/images/plants';
opendir my $dfh, $dir or die "Can't open $dir: $OS_ERROR";
my %genus_species; ## store matching entries in a hash
for my $file (readdir $dfh)
{
next unless $file =~ /.png$/; ## entry must have .png extension
my $genus = $file =~ s/\d*\.png$//r;
push(@{$genus_species{$genus}}, $file); ## push to array,the @{} is to cast the single entry to a reference to an list
}
print(encode_json(\%genus_species));
修改后的代码有效!但是,文件名不再排序。任何想法如何将 sort 合并到 encode_json 函数中?
【问题讨论】:
-
使用模块,例如Cpanel::JSON::XS
-
感谢您的见解,但我不知道如何“使用模块”。