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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.