Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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 :)

Greetz
Beatnik
... Quidquid perl dictum sit, altum viditur.


Comment on Re: Sorting
Download Code
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 :)

      Greetz
      Beatnik
      ... 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (16)
As of 2014-09-17 13:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (81 votes), past polls