Search code examples
arraysregexperlsortingperl-data-structures

Sorting an array of hashes which have alphanumeric values


I am facing an issue with sorting an array of hashes; hashes having alphanumeric values by which I need to sort.

Refer to this question! My question is an extension of this problem. I tried the solution in the above question but didn't get the required output.

$arr_ref = [
  { brand => "A.1", PO => "1.a", supplier => "X" },
  { brand => "A.2", PO => "2.a", supplier => "X" },
  { brand => "B.1", PO => "1.b", supplier => "X" },
  { brand => "B.2", PO => "2.b", supplier => "X" },
  { brand => "B.3", PO => "1.c", supplier => "Y" },
]

I need to sort by Brand or PO.

#sort the array reference and place the array back into the standard_set
$arr_ref = [sort by_brand @$arr_ref];
sub by_brand {
    $a->{brand} cmp $b->{brand}
}

Complexity is the key; can start with numeric or alphabetic character. The Brand or PO can be of different size, as well. The delimiter may be a dot or hypen.

Can we solve this depending on the input received in $arr_ref?


Solution

  • You were really close. You just need to remove the [ and ] brackets and dereference the array you want to assign to @$array_ref = ....

    use strict;
    use warnings;
    
    my $arr_ref = [
      { brand => "B.3", PO => "1.c", supplier => "Y" },
      { brand => "B.2", PO => "2.b", supplier => "X" },
      { brand => "B.1", PO => "1.b", supplier => "X" },
      { brand => "A.2", PO => "2.a", supplier => "X" },
      { brand => "A.1", PO => "1.a", supplier => "X" },
    ];
    
    my @sorted = sort { $a->{brand} cmp $b->{brand} } @$arr_ref;
    
    use Data::Dump;
    dd @sorted;
    

    Output:

    (
      { brand => "A.1", PO => "1.a", supplier => "X" },
      { brand => "A.2", PO => "2.a", supplier => "X" },
      { brand => "B.1", PO => "1.b", supplier => "X" },
      { brand => "B.2", PO => "2.b", supplier => "X" },
      { brand => "B.3", PO => "1.c", supplier => "Y" },
    )