Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^3: Extracting unique elements from array

by wink (Scribe)
on Sep 28, 2011 at 20:00 UTC ( [id://928407]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Extracting unique elements from array
in thread Extracting unique elements from array

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.

Log In?
Username:
Password:

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

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

    No recent polls found