2
votes

I have a hash like this:

%hash = ('test' => 1,
     'test1' => 2,
     'test2' => 3,);

I want to sort this hash and delete the first key value pair from hash. If I do this, (sort keys %hash)[0], I get access to first key. However, how do I delete that key value pair?

If I do

delete (sort keys %hash)[0]

Perl throws an error,

delete argument is not a HASH or ARRAY element

3
The two answers provided do sort in some stable way so that you can classify an element as "first", but they don't sort alphabetically. They sort in code-point order (we used to call it ASCIIbetical order, but in a Unicode world that doesn't quite fit anymore). Just keep that in mind. 'Z' sorts ahead of 'a', so 'Zoo' will sort ahead of 'boo'. - DavidO

3 Answers

12
votes

The expression (sort keys %hash)[0] returns a string, so you can't just pass that to delete. You have to tell delete which hash you're deleting from. It should go like this:

delete $hash{(sort keys %hash)[0]};
4
votes

First of all, hashes have no "order", but if you want to delete the entry that comes first alphabetically, you can do this:

delete $hash{(sort keys %hash)[0]};
3
votes

If you are expecting to do this operation more than once then you should keep an array of sorted hash keys.

Like this

use strict;
use warnings;

use Data::Dump;

my %hash = (
  testA => 1,
  testB => 2,
  testC => 3
);

my @keys = sort keys %hash;

dd \%hash;
while (@keys) {
  delete $hash{shift @keys};
  dd \%hash;
}

output

{ testA => 1, testB => 2, testC => 3 }
{ testB => 2, testC => 3 }
{ testC => 3 }
{}