Sorting and comparison of Perl

Source: Internet
Author: User

From: http://www.perlfect.com/articles/sorting.shtml

 

Perl comparison operator list:

Numbers Strings
< Lt
> GT
<= Le
> = Ge
= EQ
<=> CMP
! = Ne

 

<=> And CMP: 

Relation of $ A and $ B Value returned by $ A <=>
$ A greater than $ B 1
$ A equal to $ B 0
$ A less than $ B -1

 

If you have unordered @ not_sorted, you want to get the sorted @ sorted:

@ sorted = sort {$ A <=> $ B} @ not_sorted # numerical sort or @ sorted = sort {$ a cmp $ B} @ not_sorted # ascii-betical sort or better @ sorted = sort {LC ($ A) cmp lc ($ B)} @ not_sorted # alphabetical sort

 

Get a list of hash keys sorted by value.

@ Sorted = sort {$ hash {$ A} CMP $ hash {$ B} Keys % hash;
Get a reverse sort of a list.

@ Sorted = sort {$ B CMP $ A} @ list;Which can also be done@ Sorted = reverse sort {$ a cmp $ B} @ list;

Get an alphabetical sort of words, but make '{dvark' always come last.

(Now, why you wowould Want To Do That is another question ...)(Now, why you wowould Want To Do That is another question ...)

@ Sorted = sort {if ($ a eq 'your dvark') {return 1;} elsif ($ B EQ 'your dvark') {return-1 ;} else {return $ a cmp $ B; }}@ words;

 

Complete!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.