Sorting Array which is a Value in A Hash in Perl

arrays, hash, perl, sorting

Solution

In Perl, `sort` does not modify the array; it returns a sorted list. You have to assign that list somewhere (either back into the original array, or somewhere else).

@{ $hash{$item}{'lengths'} } = sort @{ $hash{$item}{'lengths'} };

Or, (especially if the array is deep in a nested hash):

my $arrayref = $hash{$item}{'lengths'};
@$arrayref = sort @$arrayref;

Your original code was sorting the array, and then throwing away the sorted list, which is why it produces that warning.

Note: As salva pointed out, by default `sort` does a string comparison. You probably wanted a numeric sort, which you get by using `sort { $a <=> $b }` instead of just `sort`:

my $arrayref = $hash{$item}{'lengths'};
@$arrayref = sort { $a <=> $b } @$arrayref;

But that has nothing to do with the warning message you asked about.

Problem

I'm trying to sort an array which is a value in a hash. The following line of code: ``` sort @{ $hash{$item}{'lengths'} }; ``` produces the following error: ``` Useless use of sort in void context at ... ```

Original source