473,703 Members | 2,297 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting data with perl - Part Two

4,059 Recognized Expert Specialist

In part one we discussed the default sort function. In part two we will discuss more advanced techniques you can use to sort data. Some of the techniques might introduce unfamiliar methods or syntax to a less experienced perl coder. I will post links to online resources you can read if necessary. Experienced perl coders might find nothing new or useful contained in this article.

Short Review

In part one I showed you some very basic syntax you can use to sort data:

Expand|Select|Wrap|Line Numbers
  1. @sorted = sort (@array); # default lexical ascending order sort
  2. @sorted = reverse sort @array; # default lexical sort in reverse/descending order
  3. @sorted = sort {$a cmp $b} @array; # same as first example
  4. @sorted = sort {$b cmp $a} @array; # same as second example
There is nothing wrong with using any of them if the data can be sorted using one of these "simple" sorts. In fact, the first example is probably the most efficient way of sorting data using perl (default ascending lexical sort). The problem is that data is rarely formatted such that you can use the default sort and get good results. But of course you can use perl to process the data to get it into a format that can be sorted. You have two options: process the data while sorting it or process the data before sorting it. Which method to use depends on your data and how much processing you need to do to sort it. Only you can determine which sorting method works best for your particular data.

Processing Data While Sorting

If you don't have much data to sort or little processing to do this can be a good option. It takes less planning and experience to get working and is generally efficient enough for most applications. For the first example we will use a list of names:

Expand|Select|Wrap|Line Numbers
  1. my @names = qw(Jim JANE fred Andrew Chris albert sally Martha);
To sort them alphabetically we need to convert them to all upper or lower case letters to avoid lexical sorting of upper case characters before lower case characters. Here is one way:

Expand|Select|Wrap|Line Numbers
  1. my @sorted = sort {lc $a cmp lc $b} @names;
We used a code block {} and perls lc (lower-case) operator to process the data while sorting it.

The sorted list:


Note that the data has not been changed, only the order. It is still in the same format of mixed case characters. The data is assigned to $a or $b and converted to lower case only during the sort comparison. What this means is that some of the data will be converted to lower case characters more than one time during the sort. This can have a big impact on how long it takes to sort data if the processing is slow. In this example, using the lc operator is marginal as far as overall performance goes. Even if it were a list of a million names it should still go pretty fast. But if you needed to use regular expressions or sorting by different fields or sorting references to data it can pay big dividends to pre-process the data before sorting.

Another way is to use a subroutine instead of a code block:

Expand|Select|Wrap|Line Numbers
  1. my @sorted = sort lowercase @names;
  3. sub lowercase {
  4.    return lc $a cmp lc $b;
  5. }
Perl treats a subroutine called by the sort function differently than other subroutines. You do not pass the data being sorted to the subroutine via @_, perl will do that internally and assign the data to $a and $b. Do not declare $a and $b with "my" even when using the "strict" pragma. They are package globals so your program will not complain about $a and $b needing to be declared with "my". And don't change or modify $a and $b. They are actually references back to the source data, so changing them could produce bizarre behavior.

You can give sorting subroutines meaningful names so it's function is understood i.e.: by_age by_date by_name by_number. Generally I find using a code block easiest for simple sorts like the previous examples and reserve using a subroutine for more complex sorts. Assume we have an array of hashes; the keys are first_name, last_name, and age.

Expand|Select|Wrap|Line Numbers
  2. my @sorted = sort by_name_and_age @array_of_hashes;
  4. sub by_name_and_age {
  5.     return    $a->{last_name} cmp $b->{last_name}
  6.               || $a->{first_name} cmp $b->{first_name} 
  7.               || $b->{age} <=> $a->{age};
  8. }
Here we introduce the || (or) operator. When perl is sorting data it returns -1 if $a comes before $b, 0 if they are the same, and 1 if $a comes after $b. If any of the comparisons returns 0, perl goes to the next comparison because of the || operator. If a comparison returns -1 or 1, perl stops comparing. If all of the comparisons return 0, the first bit of data evaluated will be listed first. Note that the age key is sorted in descending order. You can mix ascending and descending comparisons in the same sort. If the first and last names are the same, the oldest person will be listed first. If you are unfamiliar with complex data like was assumed in the last example, an array of hashes, here is a link to a tutorial on the perldoc website: Complex Data Structures.

Part three of Sorting Data with Perl will discuss methods of sorting after processing.

This article is protected under the Creative Commons License.
Dec 30 '07 #1
1 7188
4,059 Recognized Expert Specialist
Comments, corrections, discussions about this article and perls sort function are welcome. Post general perl questions in the perl forum.
Dec 30 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Xah Lee | last post by:
Today we'll write a program that can sort a matrix in all possible ways. Here's the Perl documentation. I'll post a Perl and Python version in 2 days. ----------- sort_matrix( $matrix, , , ...]) sorts a matrix by $n1 th column then $n2 th...and so on.
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) CType(local4, Short) = CType(src, Short)
by: Xah Lee | last post by:
Sort a List Xah Lee, 200510 In this page, we show how to sort a list in Python & Perl and also discuss some math of sort. To sort a list in Python, use the “sort” method. For example: li=;
by: George Sakkis | last post by:
It would be useful if list.sort() accepted two more optional parameters, start and stop, so that you can sort a slice in place. In other words, x = range(1000000) x.sort(start=3, stop=-1) would be equivalent to x = sorted(x)
by: cnsabar | last post by:
Hi., I am having the index pg no. data in file .. i need to sort the data ., Can any one help regarding this using PERL .. Its very urgent ... Source file <ce:intra-ref id="10011#f0070"/>310f, <ce:intra-ref id="10011#s0120"/>308--309 <ce:intra-ref id="10011#f0130"/>313f, <ce:intra-ref id="10011#p0310"/>313 <ce:intra-ref id="10010#p0520"/>288, <ce:intra-ref id="10010#p0550"/>284--286 <ce:intra-ref id="10007#f0010"/>146f, <ce:intra-ref...
by: KevinADC | last post by:
Introduction This discussion of the sort function is targeted at beginners to perl coding. More experienced perl coders will find nothing new or useful. Sorting lists or arrays is a very common requirement of programs. If you don't know the difference between a list and array don't worry about it. A list is just an array without a name. They both can hold the same type of data: scalars or strings. I will use the terms "list" and "array" to...
by: KevinADC | last post by:
If you are entirely unfamiliar with using Perl to sort data, read the "Sorting Data with Perl - Part One and Two" articles before reading this article. Beginning Perl coders may find this article uses unfamiliar terms and syntax. Intermediate and advanced Perl coders should find this article useful. The object of the article is to inform the reader, it is not about how to code Perl or how to write good Perl code, but to teach the Schwartzian...
by: Steve Bergman | last post by:
I'm involved in a discussion thread in which it has been stated that: """ Anything written in a language that is 20x slower (Perl, Python, PHP) than C/C++ should be instantly rejected by users on those grounds alone. """ I've challenged someone to beat the snippet of code below in C, C++, or assembler, for reading in one million pairs of random floats and
by: dorandoran | last post by:
The sort on the childgrid is not working; nothing happens when I click on the each column header for sort. (I followed Satay's sample: http://www.codeproject.com/KB/aspnet/EditNestedGridView.aspx) and i am using object for datasource. please suggest. = = = default.aspx = = <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"...
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.