Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

I'm not quite sure I understand where your confusion lies with cmp... cmp is just an operator that returns -1 if its left operand is alphabetically before its right operand, 0 if the operands are equal, and 1 if the left operand is alphabetically after the right operand.

When you use the sort function of perl, you can tell it how you want it to behave. You don't need to pass the elements of your list to $a and $b, sort will do it for you.

@abclist = qw(a b c d e); @numlist = qw(1 3 5 7 9); print sort {$a cmp $b} @abclist; // Default sort, prints 'a b c d e' print sort {$b cmp $a} @abclist; // Prints 'e d c b a' print sort {$b <=> $a} @numlist; // Prints '9 7 5 3 1' print sort {$a == 7 ? -1 : ($b == 7 ? 1 : $a <=> $b)} @numlist;

That last one is the most interesting. It ensures that 7 will always be the first element in the list... if $a is 7, no matter that $b is, we say that $a is less than $b; if $b is 7, no matter what $a is, we say that $a is greater than $b; otherwise, we do a normal <=> comparison.

Sort allows you to provide a block of code that will evaluate to a negative number, 0, or a positive number to create custom sort behavior.


In reply to Re^3: Extracting unique elements from array by wink
in thread Extracting unique elements from array by koolgirl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2024-04-23 10:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found