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

Re: sorting string

by davido (Archbishop)
on Aug 28, 2005 at 07:11 UTC ( #487227=note: print w/ replies, xml ) Need Help??


in reply to sorting string

Try this:

print "$_\n" for sort { $b <=> $a } ( $string1, $string2, $string3 )

Note, this illustrates the contortions you put yourself through by using variables such as $string1, $string2, and $string3 when you really ought to be using a proper array such as @strings. Look at how the snippet improves if you use a proper array:

print "$_\n" for sort { $b <=> $a } @array;

It could also be written as:

print map { "$_\n" } sort { $b <=> @a } @array;

Or even...

{ local $, = "\n"; print( sort( { $b <=> $a } @array ), '' ); }

By the way; the title to your question, "Sorting strings" seems to be a misnomer, since in your question you seem to be asking how to sort numeric values. Maybe I've missed the point. But if you're trying to sort ascii-betically (instead of numerically), use the cmp operator instead of <=>. This and more is discussed in sort.


Dave


Comment on Re: sorting string
Select or Download Code
Re^2: sorting string
by Anonymous Monk on Aug 28, 2005 at 08:09 UTC
    But how do I know which belong to which string? It will list something like this '123343322' so how do I save the list in a database for example? if it could list string1 = 122, string = 222, string 3 = 333... TQ

      Yes, after posting my response it hit me that your question simply didn't ask what you wanted answered.

      Zaxo has it right; you probably want a hash with key/value relationship. Then you ultimately want the strings stored as keys, and the computed values as values associated with the keys. ...something like this:

      use strict; use warnings; my %strings; # Set up some example key/value relationships. Your method # for populating the hash will be more complex, but isn't # defined in the question. $strings{"Here is one string"} = 233; $strings{"Here is another string"} = 151; $strings{"Here is yet another"} = 322; print map{ "$_ = $strings{$_}\n" } sort{ $strings{$b} <=> $strings{$a} } keys %strings;

      Dave

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2014-11-27 00:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (177 votes), past polls