in reply to complicated sorting issue

#!c:/perl/bib/perl -w $|++; use strict; my %map = ( S => 0, M => 1, L => 2, Xl => 3 ); my @sorted = map { $_->[0] } sort { ( $map{$a->[1]} <=> $map{$b->[1]} ) || ( $a->[2] cmp $b->[2] ) } map { chomp; /^\w+:\s+(\w+),\s+\w+:\s+(\w+)$/; [$_, $1, $2] } <DATA +>; print join("\n", @sorted); __DATA__ size: L, color: White size: M, color: Orange size: M, color: White size: M, color: White size: S, color: Orange size: S, color: White size: Xl, color: Orange size: Xl, color: White size: Xl, color: White

Replies are listed 'Best First'.
•Re: Re: complicated sorting issue
by merlyn (Sage) on Apr 09, 2004 at 20:02 UTC
    I'm amused that you do the mapping in the sort block, instead of properly computing the value once. Perhaps you meant:
    use strict; my %map = ( S => 0, M => 1, L => 2, Xl => 3 ); my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] or $a->[2] cmp $b->[2] } map { /^(\w+:\s+(\w+),\s+\w+:\s+(\w+))$/ ? [$1, $map{$2}, $3] : () +} <DATA>; print join("\n", @sorted); __DATA__ size: L, color: White size: M, color: Orange size: M, color: White size: M, color: White size: S, color: Orange size: S, color: White size: Xl, color: Orange size: Xl, color: White size: Xl, color: White

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      Oops, nice catch, though I would expdect you to spot such an error :). I can only say that mine does work, though with a rather less competitive performance. It's just like me to take something as dandy as the Schwartzian Transform and use it wrongly. Thanks for the correction, it will never happen again, I promise. ++ for the removal of chomp and the additional of the extra pair of capturing parentheses. Why didn't I think of that?

Re: Re: complicated sorting issue
by geektron (Curate) on Apr 09, 2004 at 20:34 UTC
    this was perfect! thanks.

      I'm not sure if you saw merlyn's correction to my mistake, so if not, please use this code instead:

      use strict; my %map = ( S => 0, M => 1, L => 2, Xl => 3 ); my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] or $a->[2] cmp $b->[2] } map { /^(\w+:\s+(\w+),\s+\w+:\s+(\w+))$/ ? [$1, $map{$2}, $3] : () } <DATA>; print join("\n", @sorted); __DATA__ size: L, color: White size: M, color: Orange size: M, color: White size: M, color: White size: S, color: Orange size: S, color: White size: Xl, color: Orange size: Xl, color: White size: Xl, color: White