in reply to Re^2: Syntax question about closures and Perl 'sort'
in thread Syntax question about closures and Perl 'sort'
Sticking some decision making inside the comparison function is not out of the question. I have an application that sorts some GUI columns. So I made a text or numeric comparison function so the low level's don't have to know what the data type is. This simplified the code. Most columns are alpha and this extra test in the compare really doesn't slow things down much - actually in this app, insignificant amount although my extra testing "looks" expensive. There is a fair amount of overhead in calling the comparison function but some easy "if" logic once you are there is not that expensive (your mileage may vary).
Anyway I would consider embedding your test for "PTR" into the a mysortfunc. test it and see if there is any significant difference. There is no need for: return sub { $a cmp $b }, the sub you are writing is the thing that will return <0,0,>0! Don't call an anon sub within your sub. Just get on with the job of returning the required value.
Oh, below I checked both $a and $b as there is some possibility of data corruption in this app. In your case, this appears to be unnecessary, just check one of them. Anyway, look at performance and you may find that something easier works very well.
sub alpha_num_cmp { my($a, $b) = @_; if (( $a =~ m/\D/) || ($b =~ m/\D/) ) { #look for a non-digit return ($a cmp $b); #string compare } return ($a <=> $b); #straight numeric comparison } #used like: sort alpha_num_cmp @array;
|
|---|