Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Sorting

by Beatnik (Parson)
on May 31, 2002 at 17:38 UTC ( #170777=note: print w/replies, xml ) Need Help??

in reply to Sorting colon-delimited records

Try something like...
@a=qw(foo:baz foo:bar); print sort { (split(/:/,$a))[1] cmp (split(/:/,$b))[1] } @a;
altho there are faster ways, like storing each second field in a hash as key :)

... Quidquid perl dictum sit, altum viditur.

Replies are listed 'Best First'.
Re: Re: Sorting
by mephit (Scribe) on May 31, 2002 at 21:39 UTC
    Hmm, comparing (split($a))[1] with (split($b))[1] was the first thing that popped into my mind, as well. But isn't that a waste of CPU cycles, splitting an element over and over again each time you wanna compare it to another? The other idea that popped into my head was extracting each "sortable" element once and storing them somewhere, (a few people had suggested a hash), so I guess it's a matter of speed or memory usage, no? For small data sets, this probably wouldn't be an issue, but maybe for larger data sets, it would. Unless the sort routine is more efficient than that, and it optimizes away rather nicely to avoid having to split the same string over and over.

    Just babbling some random thoughts. Anybody have any random answers?


    There are 10 kinds of people -- those that understand binary, and those that don't.

      Ofcourse it's slow... that's why I'm saying a faster way would be using hashes, or complex data structures for that matter... TIMTOWTDI :)

      ... Quidquid perl dictum sit, altum viditur.
      What you are describing is the basic idea behind the Schwartzian Transform. See my write-up elsewhere in this thread for some links with more information. The idea is that you do the expensive operation (in this case, it's split) once and use a data structure to store the result. You then sort on the results and extract the original information when done. Our very own merlyn was the first (AFAIK) to apply his twisted mind to this problem and come up with a very perlish (or lispish depending on your mother tongue) method of doing this in one fell swoop using map.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2021-04-12 03:33 GMT
Find Nodes?
    Voting Booth?

    No recent polls found