473,549 Members | 2,723 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting data with perl - Part Two

KevinADC
4,059 Recognized Expert Specialist
Introduction

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
  5.  
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:

albert
Andrew
Chris
fred
JANE
Jim
Martha
sally

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;
  2.  
  3. sub lowercase {
  4.    return lc $a cmp lc $b;
  5. }
  6.  
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
  1.  
  2. my @sorted = sort by_name_and_age @array_of_hashes;
  3.  
  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. }
  9.  
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 7171
KevinADC
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

2
2198
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.
7
3242
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)
20
4032
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=;
19
2892
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)
5
1856
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...
5
6672
KevinADC
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...
3
7310
KevinADC
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...
7
1909
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...
1
2940
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" ...
0
7450
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7720
Oralloy
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. ...
1
7470
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...
0
6043
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5368
isladogs
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...
0
5088
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...
0
3481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1941
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.