Jeff
Jeff

Reputation: 179

Advanced sorting of arrays

I'm having difficulty alphabetically sorting the output of my Perl script.

Here's the script:

#!/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";
}

Here's the un-sorted output:

Veronica_chamaedrys = Veronica_chamaedrys.png 
Cardamine_douglassii = Cardamine_douglassii1.png Cardamine_douglassii2.png 
Filipendula_rubra = Filipendula_rubra1.png Filipendula_rubra2.png 
Taxodium_distichum = Taxodium_distichum.png 
Asplenium_platyneuron = Asplenium_platyneuron1.png Asplenium_platyneuron2.png Asplenium_platyneuron3.png

Here's the desired sorted output:

Asplenium_platyneuron = Asplenium_platyneuron1.png Asplenium_platyneuron2.png Asplenium_platyneuron3.png
Cardamine_douglassii = Cardamine_douglassii1.png Cardamine_douglassii2.png
Filipendula_rubra = Filipendula_rubra1.png Filipendula_rubra2.png
Taxodium_distichum = Taxodium_distichum.png
Veronica_chamaedrys = Veronica_chamaedrys.png

Please advise. Thanks.

Upvotes: 1

Views: 78

Answers (1)

ikegami
ikegami

Reputation: 385829

Replace

for my $genus (keys %genus_species)

with

for my $genus (sort keys %genus_species)

If your numbers are going to reach 10, you'll want to use natsort from Sort::Keys::Natural (1, 2, ..., 9, 10, ...) instead of the builtin sort (1, 10, 11, ..., 2, ...), at least for the one sorting the file names.

Upvotes: 8

Related Questions