in reply to Sort based on a delimited field in array elements without affecting original array elements

Take a look at the Schwartzian or Guttman Rosler Transforms, both of which are ideal for this kind of (and more advanced!) sorting ...

@array = map { $_->[0] } # strip meta data sort { $a->[1] <=> $b->[1] } # sort by meta data map { [ $_, /([^!]+)/ ] } # build meta data @array;

You might also want to check out japhy's Resorting to Sorting tute.

Update: Tweaked the example for readability.

    --k.

  • Comment on Re: Sort based on a delimited field in array elements without affecting original array elements
  • Download Code

Replies are listed 'Best First'.
Re^2: Sort based on a delimited field in array elements without affecting original array elements
by tadman (Prior) on Mar 01, 2002 at 23:36 UTC
    Speaking of Schwartzian transform, is there a simple way to define a ST-method and then apply it to different circumstances? The problem is felt when trying to sort two different kinds of things, yet without having to write the ST again and again, each time with a minor change.

    Consider:
    my @blobs = map { $_->[0] } sort {$a->[1] cmp $b->[1] } map { [$_, $_->property_foo()] } @blob_list; my @flobs = map { $_->[0] } sort {$a->[1] cmp $b->[1] } map { [$_, $_->function_bar()] } @flob_list;
    You can do this with C++ templates. How, though, in Perl, though without using eval or sacrificing the value of warnings when passing bad function names?
      sub ST(&@){ my $metric=shift; map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_,&{$metric}]} @_ }