Perl hash output sorting

Source: Internet
Author: User

Sort Function

Sort list
Sort Block List
Sort subname list

The usage of sort is as follows. It sorts the list and returns the sorted list. If the subname or block is ignored, sort is performed in the standard string comparison order (for example, ASCII order ). If subname is specified, it is actually the name of the sub-function. This sub-function compares two list elements and returns an integer smaller than, equal to, or greater than 0, this depends on the order in which the elements are sort (ascending, constant, or descending ). You can also provide a block as an anonymous sub-function to replace subname. The effect is the same.

The two elements to be compared are temporarily assigned to the variables $ A and $ B. They are passed as references, so do not modify $ A or $ B. If a subfunction is used, it cannot be a recursive function.

If the key is sorted by ASCII

Foreach my $ item (sort {$ a cmp $ B} Keys % hash ){
Print "$ item ==>$ hash {$ item}", "/N ";
}

If the keys are sorted in reverse ASCII orderCodeSet
$ A and $ B are exchanged.


IfValueFollowASCII sorting

foreach my $ item
( sort {$ hash {$ A} CMP $ hash {$ B} Keys % hash ) {
Print" $ item =>$ hash {$ item} ","/N ";
}

if you set the value to ASCII inverse sorting,
$ hash {$ A} and
$ hash {$ B} interchange.

if you sort by number, the code is similar to the preceding one, only replace
CMP with a symbol <=>. Take the key as an example:

foreach
my $ item (sort {$ A <=> $ B} Keys % hash) {
Print" $ item =>$ hash {$ item} ","/N ";
}

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.