I have a list of strings with the following format:
('group1-1', 'group1-2','group1-9', 'group2-1','group2-2', 'group2-9','group1-10', 'group2-10' )
I need them to be sorted as below:
group wise first and then number wise.
('group1-1', 'group1-2','group1-9','group1-10', 'group2-1','group2-2', 'group2-9', 'group2-10' )
I've written following code, but it's not working as expected: a comparator that sorts based on the group and if the groups match, it sorts based on the number.
my @list = ('group1-1', 'group1-2','group1-9',
'group2-1','group2-2', 'group2-9','group1-10', 'group2-10' );
@list = sort compare @list;
for (@list){
print($_."\n");
}
sub compare{
my $first_group, $first_num = get_details($a);
my $second_group, $second_num = get_details($b);
if($first_group < $second_group){
return -1;
} elsif($first_group == $second_group){
if ( $first_num < $second_num) {
return -1;
} elsif ( $first_num == $second_num ) {
return 0;
} else {
return 1;
}
} else{
return 1;
}
}
sub get_details($){
my $str= shift;
my $group = (split /-/, $str)[0];
$group =~ s/\D//g;
my $num = (split /-/, $str)[1];
$num =~ s/\D//g;
return $group, $num;
}