in reply to Accessing $a and $b of 'sort' across package boundaries

Use the alternate usage of sort:

foreach ( sort gs::long_strings_first @$raw_hash_keys_ar ) { #do_stuff; } package gs; sub long_strings_first($$) { return 0 unless defined $_[0]; return 0 unless defined $_[1]; length $_[1] <=> length $_[0] || lc $_[1] cmp lc $_[0] }

Why did you check if $b is undefined and not $a? If there can be undefined values in the list to be sorted, both $a and $b could be undefined. I added the extra check.

Replies are listed 'Best First'.
Re^2: Accessing $a and $b of 'sort' across package boundaries
by davidrw (Prior) on Jun 06, 2005 at 19:26 UTC
    Is that usage of sort any better/worse/different than something like this?
    foreach ( sort gs::long_strings_first($a,$b), @$raw_hash_keys_ar ) { #do_stuff; } package gs; sub long_strings_first { my ($first, $second) = @_; ... }

      Yes, I think there's a substantial difference in performance. Feel free to Benchmark.

      Also, doing my ($first, $second) = @_; instead of referencing $_[0] and $_[1] directly adds to the cost. It doesn't give anything in return either, since the names are no more descriptive than $_[0] and $_[1].

        ah. That makes sense -- i figured it was something like that. So is there any difference in these two, assuming the long_strings_first is how you defined it (using $_[0] and $_1 directly)?
        sort gs::long_strings_first @$raw_hash_keys_ar; sort gs::long_strings_first($a,$b) @$raw_hash_keys_ar;
        (first one seems better in appearence, but just curious if any techincal sort-magic difference)
Re^2: Accessing $a and $b of 'sort' across package boundaries
by ff (Hermit) on Jun 06, 2005 at 19:28 UTC
    Actually that return 0 unless defined bit was a ghastly way of checking whether there was even something to sort. Thanks for your interpretation and improvement of my lines. :-) (And thank you for the illustration of this other way of using sort that I didn't know/think about before. I've needed this for a while....)