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

Re: Sorting an array of strings by number

by jeroenes (Priest)
on Oct 01, 2001 at 16:05 UTC ( #115835=note: print w/replies, xml ) Need Help??

in reply to Sorting an array of strings by number

There is more than one path to take here:

  1. Zero-pad your numbers, so generate them with
    my $padded=sprintf("%08.3f",39.452);
    You can do this while reading your data:
    while (<>){ split /:/; $_[0]=sprintf("%08.3f", $_[0]); push @data, join ":", @_; }
  2. Or you can sort numerically. This requires you to extract the numbers and sort on them with <=> (see perlop), like
    sort{ $a <=> $b} @numbers;
    . You can write a sub for the extraction:
    sort{extract( $a ) <=> extract( $b )} @lines; sub extract{ $a = shift; split /:/, $a; $_[0]; }
  3. It's better to extract your numbers, and use them as keys in a hash, and work with a list of sorted keys:
    my %hash; while(<>){ my ($key, $data) = split( /:/, $_, 2 ); $hash{ $key } = $data; } print "Sorted!:\n\n", join "|", sort {$a <=> $b} keys %hash;
  4. .... many more paths to come up with


"We are not alone"(FZ)
(code untested, you'll get the idea)

Albannach is right of course. Still, if you have quite some data, a hash-lookup is more efficient. And more scalable, as you can tie your hash onto a database, e.g. To prevent that double-count problem, add a check in for the key, if a double, add a counter or something.

$key .= ':001' if defined $hash{$key}; $key++ while defined $hash{$key};

Replies are listed 'Best First'.
Re: Re: Sorting an array of strings by number
by Albannach (Prior) on Oct 01, 2001 at 17:27 UTC
    Note that in your option 3 the unique keys of the hash will be likely to clobber some data as the anonymonk specified that the first value is price in his problem. Hashes are great for many reasons but this example is easily and simply addressed by a simple numerical sort so unless there is reason to need to search the data by price, and a certainty of unique pricing, I'll go with one of your first two options.

    I'd like to be able to assign to an luser

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://115835]
[stevieb]: Torturing one of my dev RPis to turn four 5v stepper motors at the same time (via Parallel:: ForkManager for 50k degrees (a whole lot of full turns!). Let's see if it burns out or not.

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2018-03-22 22:14 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (286 votes). Check out past polls.