Perl: sorting by string

I have an array full of string values that need to be sorted, but if a value starts with (regex) 0^[SV] it should be at the beginning of the array. Otherwise the array should be sorted normally using ascii sort.

Please help me create the sub to pass to the sort function.

show some examples

It will look like this before:

and after

here's one idea
1) got through each element of the array, check for ^0[SV], if yes, push to array1. at the same time, those not ^0[SV] , push to array2
2) sort array1 ( using sort function), and array2
3) join the new arrays together, putting array2 behind array1

Write your own sort-sub, more in perldoc -f sort

Thanks. I figured it out.

sub Bysite {
    if ( $a =~ /^0[SV]/ ) {
        return -1;
    }
    elsif ( $b =~ /^0[SV]/ ) {
        return 1;
    }
    lc($a) cmp lc($b);
}

@array = sort Bysite @array;

Thats a good solution but it will not sort your sample array into what you posted:

0S09
0S22
0V54
0V72
0A13
0H98
0L43
EL24
STB45

it sorts a little differently:

0S22 <--
0S09 <--
0V54
0V72
0A13
0H98
0L43
EL24
STB45

but maybe close enough is OK :slight_smile:

Thanks. For this particular case, close enough is ok.