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 ...
my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash; From there we can get more complex. If the hash values are the same, we can provide a secondary sort on the hash key.
Perl's built in sort function allows us to specify a custom sort order. Within the curly braces Perl gives us 2 variables, $a and $b, which reference 2 items to compare. In our case, these are hash references so we can access the elements of the hash and sort by any key we want.
Elements of hash can be anything, including references to array.
If you want to access a Hash in a sorted manner by key, you need to use an Array as an indexing mechanism as is shown above. This works by using the Emmuerator#sort_by method that is mixed into the Array of keys. #sort_by looks at the value my_hash[key] returns to determine the sorting order.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With