in reply to Re^2: Sorting array
in thread Sorting array

On closer inspection, this doesn't seem to be quite a complete solution. The below section of the approach I think is expected to return the replaced value, in this case 'ID'.

It instead returns a 1 if a replacement is made or an empty string if it is not. It happens to produce the correct sort in this case because of the narrow data set used.

my $string = 'ID13'; say scalar( $string =~ s/\d+// );

Does anyone else know of a way to return the correct match in place of this line? The below is a very poor solution I expect.

my $string = 'ID13'; say join('', grep( /[A-Za-z]/, split('',$string) ) );

Replies are listed 'Best First'.
Re^4: Sorting array
by Anonymous Monk on Sep 24, 2011 at 17:12 UTC

    It happens to produce the correct sort in this case because of the narrow data set used.

    Actually it doesn't produce a correct sort, its very close, but not correct. But it does match your sort exactly :)

    In any case, I find having more than one cmp confusing, so I usually just pad zeros where appropriate, like

    #~ @sorted = map { $_->[0] } @sorted = map { sprintf '%-20s %s', @$_ } sort { $b->[1] cmp $a->[1] } map { my $f = $_; no warnings 'uninitialized'; my( @didots ) = split /[.]/, ( /-([.\d]+)/ )[0]; my $ret = sprintf( '%01d.%01d.%01d ', @didots); ## %03d%03d%03d should be sufficiently futureproof if(my( $digits ) = /ID(\d+)-/ ){ $ret = "1 $ret".sprintf( '%03d ', $digits ) } else { $ret = "0 $ret"; } [ $f, $ret ]; } @unsorted; print Dumper( \@sorted ); __END__ $VAR1 = [ 'ID15-ABC-6.1 1 6.1.0 015 ', 'ID3-ABC-6.1 1 6.1.0 003 ', 'ID12-ABC-5.1.5 1 5.1.5 012 ', 'ID5-ABC-5.1.5 1 5.1.5 005 ', 'ID12-ABC-5.1 1 5.1.0 012 ', 'ID9-ABC-5.1 1 5.1.0 009 ', 'ID5-ABC-5.1 1 5.1.0 005 ', 'ABC-6.1 0 6.1.0 ', 'ABC-5.1.5 0 5.1.5 ', 'ABC-5.1 0 5.1.0 ' ];

    Usually pad to 3 digits is sufficient, but sometimes I need to go to 20