Sorting an array, which is a hash value in Perl

I am trying to sort an array which is the value in the hash . The following line of code:

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

produces the following error:

Useless use of sort in void context at ...
+5
source share
4 answers

Perl sortdoes not modify the array; it returns a sorted list. You should assign this list somewhere (either back to the original array, or somewhere else).

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

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

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

Your source code would sort the array and then throw away the sorted list, so it gives this warning.

.. salva , sort . , , sort { $a <=> $b } sort:

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

, .

+6

Perl sort " ". , . cjm,

(. )

+3

, , :

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

-

my %lrn_hash;

$lrn_hash{1} = 1;
@{$lrn_hash{1}{VALS}} = (6,7,1,5,7,9);

@narr = sort @{$lrn_hash{1}{VALS}};
print "@narr\n";

,

1 5 6 7 7 9

perl u?

-2

All Articles