Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^2: What is "Schwartzian Transform"

by monarch (Priest)
on Jul 21, 2005 at 07:51 UTC ( [id://476736]=note: print w/replies, xml ) Need Help??


in reply to Re: What is "Schwartzian Transform"
in thread What is "Schwarzian Transform" (aka Schwartzian)

How is the sort named after one of the many perlmonks here any more advantageous than a simple:
use strict; my @data = ( ['-r--r--r--','1','yourname','8318','2000-01-01','ant.txt'], ['-r--r--r--','1','yourname','11986','1992-12-30','tiger.txt'], ['-r--r--r--','1','yourname','72698','2004-03-03','duck.txt'], ['-r--r--r--','1','yourname','46852','1788-01-26','goose.txt'] ); print( "Which column to sort on?" ); my $column = ( <STDIN> =~ m/^\d+$/ ); exit( 1 ) if ( ! defined($column) ); my @sorted = sort { $a->[$column] cmp $b->[$column] } @data; print( join( "\n", map { join( ",", @{$_} ) } @sorted ) );

IE, just select the column (or hashref) you want to sort on.

update: I very much like kelan's answer to this post, it indeed shows one area where this other process comes in useful.

Replies are listed 'Best First'.
Re^3: What is "Schwartzian Transform"
by kelan (Deacon) on Jul 21, 2005 at 12:28 UTC

    The usual use is when the sort key must be derived from the data using a process that takes significant time/resources. The idea of the ST is to precalculate all of the sort keys before the sort operation so you only spend the time once:

    @sorted = map { $_->[ 1 ] } sort { $a->[ 0 ] <=> $b->[ 0 ] } map { [ expensivefunc( $_ ), $_ ] } @data;
    Doing a naive sort, you would be calling that expensive function twice for every comparison, which would end up being a lot more than when precalculating:
    @sorted = sort { expensivefunc( $a ) <=> expensivefunc( $b ) } @data;

      In all recent examples, I've moved the "original key" to tuple element 0, so that the first step is consistently  map $_->[0] regardless of how many "expensive" keys are computed.

      Just a minor nit.

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://476736]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-18 18:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found