Reputation: 179
I want to modify my Perl script to output a list of variables using the json_encode function, but I'm not sure how.
Here's the output of my unmodified Perl script:
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
The variables to the left of the equal signs are plant names, and the one or more file names to the right of the equal signs are plant photos. Notice that these file names are not separated by commas.
Here's my Perl script that generated the above output:
#!/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";
}
Please advise how to output these variables in a JSON array. Thanks.
Update... Here's the revised script with the recommended changes per a forum member:
#!/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));
This revised code works! However, the file names are no longer sorted. Any ideas how to incorporate sort into the encode_json function?
Upvotes: 1
Views: 167
Reputation: 37472
Pretty straight forward actually... You can use the JSON::PP module and pass a reference of your hash to encode_json()
.
#!/usr/bin/perl
use strict;
use warnings;
use JSON::PP;
# your other code goes here...
# instead of `for my $genus (keys %genus_species) { ... }` do:
print(encode_json(\%genus_species));
Upvotes: 3