Developer
Developer

Reputation: 6350

Compare string values inside a hash in Perl

I want to sort this hash in alphabetical order .This is my hash structure

my $hash = {
          'names' => [
            {
              'state' => 'I',
              'names' => 'INTTEST',
            },
            {
              'state' => 'I',
              'names' => 'TEST',
            },
            {
              'state' => 'D',
              'names' => 'GREATTEST',
            },
            {
              'state' => 'I',
              'names' => 'Stest',
            },
            {
              'state' => 'I',
              'names' => 'Atest',
            },
            {
              'state' => 'D',
              'names' => 'SPtest',
            },
            ]
        };

What i have tried is

my @sorted_data = (sort { lc($b->{names}) cmp lc($a->{names});} $hash->{names});

I want to return the same structure to the user.

Upvotes: 0

Views: 242

Answers (1)

mpapec
mpapec

Reputation: 50637

You have to dereference $hash->{names} array,

use feature 'fc';
my @sorted_data = sort{ fc($b->{names}) cmp fc($a->{names}) } @{$hash->{names}};

fc checks if two strings are equal regardless of case

If you want to sort in place, just assign result back to originating array,

@{$hash->{names}} = sort{ fc($b->{names}) cmp fc($a->{names}) } @{$hash->{names}};

Upvotes: 2

Related Questions