Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing first key value pair from hash

Tags:

perl

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

like image 242
user238021 Avatar asked Nov 29 '25 06:11

user238021


1 Answers

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]};
like image 115
Alan Curry Avatar answered Nov 30 '25 23:11

Alan Curry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!