ewok
ewok

Reputation: 21463

perl: sort arrayref inside a hashref

I have the following structure:

my $hsh = {
  arr => [
    1,
    3,
    6,
    4,
    2
  ]
}

I want to sort $hsh->{arr}, but I can't figure out how. sort $h->{arr} doesn't work.

Upvotes: 0

Views: 91

Answers (3)

Kosh
Kosh

Reputation: 18393

$hsh->{arr} = [sort @{$hsh->{arr}}];

Upvotes: 0

ikegami
ikegami

Reputation: 385847

sort @{ $hsh->{arr} }

References about references:


If you want to sort in-place[1], use:

@{ $hsh->{arr} } = sort @{ $hsh->{arr} };

If you want to create a new array:

my @a = sort @{ $hsh->{arr} };

If you want to create a new anonymous array:

my $a = [ sort @{ $hsh->{arr} } ];

  1. This doesn't just effectively sort in place, but actually does sort in-place. because sort is optimized to sort in-place when you have something of form ARRAY = sort ARRAY (or with a compare block of function).

Upvotes: 1

ysth
ysth

Reputation: 98398

sort @{ $hsh->{arr} }

See http://perlmonks.org/?node=References+Quick+Reference.

Upvotes: 3

Related Questions