Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Array which is a Value in A Hash in Perl

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 ...
like image 489
syker Avatar asked Dec 08 '10 07:12

syker


People also ask

How do I sort a hash value in Perl?

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.

How do I sort an array of hash in Perl?

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.

Can a Perl hash value be an array?

Elements of hash can be anything, including references to array.

How do you sort hash values?

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.


1 Answers

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.

like image 181
cjm Avatar answered Sep 27 '22 19:09

cjm