Perlfect Solutions  

Sorting Techniques


Sorting is a commonly needed operation in all kinds of programs. Luckily, for us perl programmers, perl provides a very simple yet extremely powerful mechanism to accomplish any sort you might think of. This article is about teaching the novice programmer how to sort lists of things, while showing to the more experienced folks certain techniques and ideas that could be new to them if they are migrating from a different language.

Moving to the meat of the matter staight away, we'll start from talking about comparison. Obviously, in order to put a list of things in order, you'll have to first define that order. Order is defined by how things compare to each other. If I give you two items from the list, can you tell me which one is bigger / better / nicer / sexier ... [insert you favourite adjective here] than the other? Or tell me thet they are both of equal order? Well, that's just about it! If you give me a list of items and promise me that you can answer this question for any pair of them, I can make a sorted list of them. All I have to do is take all possible pairs and ask you "how do these two compare?" and arrange them accordingly to finally come up with a sorted list. Actually there are even smarter ways to do it, minimising the amount of comparisons needed, but that is not an issue here, as we will see soon that perl performs that task for us, and we trust perl that it uses the least expensive method.

Now, the issue in question being comparison, I assume you must be familiar with all (or at least most) of perl's comparison operators. There's a list of them:

Numbers Strings
< lt
> gt
<= le
>= gr
== eq
<=> cmp

Now the first five rows should be ok, they're just like math. But what are the <=> and cmp operators? Basically, the expression $a <=> $b (or $a cmp $b for strings) returns one of the values 1, 0, -1 if $a is, respectively, larger, equal or lower than $b. (see table below)

Relation of $a and $b Value Returned by $a <=>
$a greater than $b 1
$a equal to $b 0
$a less than $b -1

Does that ring a bell? Coming to think of it, the <=> and cmp operators actually provide the answer to the question we were investigating earlier when we talked about how to sort by using a comparative criterion. So, if we already have an operator that answers this question ("how do two items compare?") all we need is a function that will take a list of items and perform the necessary comparisons to arrive at a sorted list. And guess what? That's exactly what perl's sort operator does. So, if you have an unsorted list @not_sorted and want to created a sorted list @sorted, you just say:

@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

Looking at the sort function, we notice that it is exactly as we described it in words, earlier in this article. Perl needs just two things: the list of items to sort, and a subroutine that answers the question "how do these two compare?" for any pair of items in the list. Perl puts the two items it want to compare int the special variables $a and $b and your function is responsible to give a return value that corresponds to the existing relationship of the two, as shown in the table shown earlier.

Here, in this simple example, we used perl's built-in comparison operators that work for numerical and alphabetical (not realy... to be correct it is ASCII order) sorting. Of course, you can roll your own comparison function to create sorts for any kind of ordering you wish to have. Before you start coding your own functions, take a look to the following examples:

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 with @sorted = reverse sort { $a cmp $b } @list;

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

(Now, why you would want to do that is another question...)

@sorted = sort { if ($a eq 'aardvark') { return 1; } elsif ($b eq 'aardvark') { return -1; } else { return $a cmp $b; } } @words;

  Save This Page  


Your name:
Your comments:

Security check *


Dr Vee   

Posted at 5:39pm on Thursday, March 8th, 2007

Googled over a dozen of other pages, nothing comes close to this. THANKS ALOT!


Posted at 1:52am on Tuesday, March 13th, 2007

how to sort the the array of items which contains list of file names. these can distinguished by date


Posted at 2:18pm on Friday, March 23rd, 2007

yahooed one page, and this was it, i did not have to google 20 pages.


Posted at 12:34am on Saturday, March 31st, 2007

simple and to the point article . Thanks a lot.


Posted at 1:34pm on Sunday, April 1st, 2007

Wonderful article, helped a lot.


Posted at 7:02am on Thursday, April 5th, 2007

reverse sorting was made very clear after seeing this example :)


Posted at 3:07pm on Thursday, April 5th, 2007


I had an array like this:
$fileNames[0] = logfile200704050000
$fileNames[1] = logfile200704050050
$fileNames[2] = logfile200704050812
$fileNames[3] = logfile200704050225

and sorted them like this:

@sorted = sort { substr($a,8,12) substr($b,8,12) } @fileNames;


Posted at 3:10pm on Thursday, April 5th, 2007

The website took out the operator on the last line. It should look like this without the spaces on either side of the '='
@sorted = sort { substr($a,8,12) < = > substr($b,8,12) } @fileNames;


Posted at 1:33am on Wednesday, April 18th, 2007

Great page, very useful! Simplified some pretty tricky problems I was having.

Randal L. Schwartz   

Posted at 4:52am on Thursday, April 19th, 2007

I have plenty of examples of using Perl's sort (including the now-famous "Schwartzian Transform", named after me, but not BY me) at my 250-magazine articles available on my website. Use a google search of "sort" (but without the quotes) and have fun reading.


Posted at 2:07am on Friday, April 27th, 2007

How do you sort for example chapters in a book? They go like 1, 1.1, 1.1.1, 1.1.2, 1.2, 1.3, 2, 2.1, etc...
Numeric sort just won't put it in that order.


Posted at 7:15am on Friday, June 15th, 2007

Depending on how deep the book is, you could strip the .'s, then pad right with 0's so all values are 4 digits long. e.g:

1000 (was 1)
1100 (was 1.1)
1120 (was 1.1.2)
1200 etc

So you need to strip the ".", then pad. Look for replace and sprintf.


Posted at 8:34am on Friday, July 13th, 2007

Awesome article. Poured over ton of sites, and this article is like the most concise, to the point article. Read first 8 lines, implemented my sort function inline and I was good to go. You should bill my company!


Posted at 2:54am on Wednesday, July 18th, 2007



Posted at 11:18am on Wednesday, July 18th, 2007

good job, also would be nice to add a paragraph about how the interpreter compares the strings.
for example
baaaaaa> azzzzzzz


Posted at 1:54pm on Wednesday, July 25th, 2007

If you have a list of hash refs and you want to sort by two values (for example, sort primarily by people's ages, but if the ages are the same, sort alphabetically), do something like this:
@sorted = sort { ($a->{age} $b->{age}) || ($a->{name} cmp $b->{name}) } @not_sorted;

Willem Kernkamp   

Posted at 8:46am on Monday, July 30th, 2007

To the point and concise! Thanks a lot.


Posted at 1:44am on Thursday, August 9th, 2007

"Get an alphabetical sort of words, but make 'aardvark' always come last.
(Now, why you would want to do that is another question...) "

This was exactly what I needed, thanks very much!


Posted at 12:14am on Wednesday, August 15th, 2007

You can also sort a hash of hashes (or hash of arrays or whatever) based on values in any subscript as such:
sort { $not_sorted{$a}{name} cmp $not_sorted{$b}{name} } keys %$not_sorted;

... useful where you might have multiple properties for each element, as it allows you to sort on any given property. Can of course be combined with mcb's method for sorting on multiple criteria.


Posted at 12:15am on Wednesday, August 15th, 2007

typo in the above, should be:
sort { $not_sorted{$a}{name} cmp $not_sorted{$b}{name} } keys %not_sorted;


Posted at 11:46pm on Wednesday, August 15th, 2007

thank you! teh 1 minute bugfix before the release ;)


Posted at 4:57am on Friday, August 17th, 2007

This is one kind of sort you did not talk about. You want to sort the following: Die Hard, Die Hard 2, Die Hard 3. The sort function will put Die Hard last. I do not want to add a 1 for Die hard. How would you make a sort to fix this problem? Thanks


Posted at 4:27am on Tuesday, August 21st, 2007

So clear and so helpful! Thanks!


Posted at 7:44pm on Wednesday, August 22nd, 2007

There appears to be a mistake in the last section of the article (making 'aardvark' always come last). I've recently had to use something similar to this, and the way it's written here will actually force 'aardvark' to always come _first_, not last. Reverse the return values (-1, 1) to correct this.


Posted at 7:28am on Thursday, August 23rd, 2007

@Daniel: Thanks for spotting that. I have updated the article above.


Posted at 4:13pm on Wednesday, August 29th, 2007

How can I sort a sub-array based on the order another array?


Posted at 7:39am on Tuesday, September 4th, 2007

My application requires sorting of a large hash (> 100,000,000), but I am only interested in the largest 50,000 entries. Is there an economical way to first get the largest 50,000 entries (all floats) and then sort only those rather than sorting the whole hash?


Posted at 11:35pm on Tuesday, October 2nd, 2007

To decide to which are the largest 50000 entry you need to short the whole thing first.


Posted at 7:12am on Tuesday, October 9th, 2007

David, the most efficient algorithm to find the largest i elements out of n elements works in expected linear time O(n) (as opposed to at least O(n log n) for sorting). Pacman is wrong. The algorithm is similar to quick sort, partitioning the array repeatedly but always making just one recursive call to the half where the split should occur (in your case where the position 50000) is. You should check out the Intro to Algorithms book or find information on Selection (order statistics) on the web somewhere to get details. This procedure is significantly faster especially when you deal with such a huge array of 100 mil. elements.


Posted at 1:20am on Wednesday, October 17th, 2007

How Sort numeric array or Character array without using sort function in Perl


Posted at 12:51am on Friday, October 26th, 2007

"Get an alphabetical sort of words, but make 'aardvark' always come last.
(Now, why you would want to do that is another question...) "

Seriously, this helped me a lot for my taks. Thanks a lot


Posted at 7:03am on Tuesday, October 30th, 2007

So how do I get the sort to ignore the case of the characters?


Posted at 4:45am on Friday, November 2nd, 2007

Continuing on from the the previous comment I used @sorted = sort { lc $hash{$a} cmp lc $hash{$b} } keys %hash; to sort with upper and lower cases mixed and it does not work.


Posted at 6:53am on Friday, November 2nd, 2007

@Brenda: Is your intention to sort the *values* of the hash according to its *keys* in a case insensitive way?

Perhaps what you intended to do is:
@sorted = sort { lc $a cmp lc $b } keys %hash;
which will give you the keys of the hash sorted as you desire.


Posted at 10:37am on Thursday, November 29th, 2007

MCB - your comment really helped...thanks a TON


Posted at 11:19pm on Tuesday, January 15th, 2008

when sorting the list the words in uppercase are given highest priority than words in lowercase. why is it so???

John W. Krahn   

Posted at 5:57pm on Wednesday, January 16th, 2008

Your table of comparison operators has one error and one omission.

>= gr

That should be:

>= ge

And you are missing:

!= ne



Posted at 5:47am on Monday, January 21st, 2008


Mark T   

Posted at 3:14am on Thursday, January 31st, 2008

When sorting words and digits, do the words always appear first?


Posted at 6:43am on Thursday, January 31st, 2008

I am trying to sort on a value within a hash of hashes. 'Trade' is the key to the value which is a number. Pls can anyone advise on the syntax?

The key is at the following level:

foreach my $instrument( sort{$tradeSummary{top25}{Trade}{$a}$tradeSummary{top25}{$instrument}{Trade}{$b}} keys %{$tradeSummary{top25}} ){


Posted at 7:36am on Thursday, January 31st, 2008

I've managed to resolve this referencing issue. The Trade value actually belonged in the first item of an array, so the following worked:

foreach my $instrument (sort {$tradeSummary{top25}{$b}[0]$tradeSummary{top25}{$a}[0]} keys %{$tradeSummary{top25}} ){


Posted at 9:41pm on Thursday, February 21st, 2008

Fantastic article! Helped me in my Perl/CGI programming course.


Posted at 7:53pm on Thursday, March 6th, 2008

Very nice article. Helped me a lot.

Anupam Nandan   

Posted at 4:47am on Wednesday, March 19th, 2008

gud work ..


Posted at 11:14am on Friday, March 28th, 2008

I want to sort a file where the starting is the file name followed by the sequence
, how do i sort these two
>ugast 1234....
> ecoli12k12

I just want the sequence and not the line staring with >


Posted at 4:59am on Tuesday, April 22nd, 2008

how about random order:

sort { int(rand(3))-1 } @table

Thor Is my Real Name and I'm not Swedish   

Posted at 11:40am on Friday, April 25th, 2008



Posted at 8:48am on Tuesday, April 29th, 2008

I am new to perl
how can we do sorting in hash value - currently using following code

for (my $i = 0 ; $i< $#docs ; $i++) {
for (my $j = 0 ; $j< $#docs-$i ; $j++) {
if( $docs[$j]->{"LAST_MODIFIED"} > $docs[($j+1)]->{"LAST_MODIFIED"} )
my $temp = $docs[$j+1];
@docs[$j+1] =$docs[$j] ;
@docs[$j] = $temp;


Posted at 11:17am on Wednesday, May 14th, 2008



Posted at 11:48am on Friday, June 6th, 2008

google 1 time
string = "perl sort"
got me this link on 1 link! hauhauhuau
it all depends on how is googling! ;)


Posted at 5:01am on Tuesday, July 29th, 2008

excellent article on the cmp operator. thank you. :)


Posted at 11:54pm on Monday, August 11th, 2008

How to remove duplicate entries from an array?

My task is to remove duplicate entries from $PATH


Posted at 12:22pm on Sunday, August 17th, 2008

sort by T#

perl god   

Posted at 11:30am on Tuesday, August 26th, 2008

nice website. I will tell my mommy about it.

Michael Martin   

Posted at 3:53am on Wednesday, August 27th, 2008

More Perl articles need to be written in a similar style and format. This is an excellent article.


Posted at 2:46pm on Wednesday, August 27th, 2008

I want to sort the following alphanumeric list:
@list = {C20,RL20,C3,BAT10,C9,RL190,BAT8,C101,RL4}

I do:
@sorted = sort { $a cmp $b } @list;

The sorted result is:


What I'm doing wrong ??


Posted at 4:08am on Wednesday, September 3rd, 2008

You're sorting on the string and, for instance, BAT1 < BAT8
and so BAT10 < BAT 8 the same way alps comes before alt in a dictionary.

What you want is natural sort (?) If you've not found it already, look at


Posted at 12:41pm on Monday, September 8th, 2008

My situation is slightly different than vortex's:

@datesearch = sort {$b $a}} @datesearch;

where each record in @datesearch is:


so it sorts these two data points as follows:

07101418mm duration version
080906semroc space

Where as is should be the other way around. I tried the recommendations using substr($a,0,6), and cmp verses , but can't seem to influence change here.

Help!? and thanks.


Posted at 1:12pm on Monday, September 8th, 2008

As long as I'm here and asking... does perl sort have a limit in the size that it compares? If I have have a text that is 256 charaters and only different on the last character.. will it sort it? Should I work to reduce the length of the strings to increase speed?


Posted at 12:44am on Tuesday, September 30th, 2008

How should i sort array @fxed=[1,23][2,21][3,87]...
Array is populated on loop ($fxed[$i])=join(",",$i,$e[$i]);


Posted at 8:16am on Monday, October 6th, 2008

Help, I have these loops.....

foreach $i (0..$counter){
foreach $j ($i..$counter2){
open DAT, ">>$vec2[$j][2].dat";
push (@data, $vec2[$j][3], $vec1[$i][1]);
printf DAT "$vec2[$j][3] $vec1[$i][1]n";

And it brings me out these info into a file :
1 391.692
4 -167.747
2 2.82568
3 200

What I want its that info sorted from min to max
1 391.692
2 2.82568 and so on, etc etc....

I have tried this inside the loops but nothing happens! please what can I do? THANKS A LOT !

@data_s= sort {$a->[0]$b->[0]}@data;
printf DAT $data_s[$j][$i];


Posted at 2:04pm on Wednesday, October 8th, 2008

hi can any one sort the numbers without using sorting techniques


Posted at 4:24pm on Thursday, October 9th, 2008

First thing I notice is the unconditional 'last' call in the inner loop, which would seem to defeat the purpose of even having an inner loop. The following code is functionally equivalent to what you had above:

foreach $i (0..$counter){
open DAT, ">>$vec2[$i][2].dat";
push (@data, $vec2[$i][3], $vec1[$i][1]);
printf DAT "$vec2[$i][3] $vec1[$i][1]n";

However I suspect that this would be a lot simpler if you:
A) drop the counter variables and loop over you array elements directly (after sorting as required), optionally use the 'for $i ( 0 .. $#vec2[.. )' construct if you really need to know $i
B) drop the [3] element in the final subscript of your array - it appears to just be a line number for the output, which would be better to generate inside the print loop rather than have it tied to the array.

Keep in mind this is based on some assumptions which may not be correct, so you might be better to go back and read the following tutorials at

Sorry I didn't answer your question directly, but I really think that without a better understanding of the topics discussed in those tutorials above you'll just run into more problems.



Posted at 4:37pm on Thursday, October 9th, 2008

@yakeeen & Sujeet:
You're asking if you can sort without sorting? I'm confused. If you want a list sorted, you use these sorting techniques. You can of course roll-your-own sorting method instead, but using perl's native 'sort' function is by far the quickest, easiest and most efficient, so in almost all cases you are best to use it. Read and then this page again if you don't understand how best to use it.

Jonathan Leto   

Posted at 11:06pm on Friday, October 10th, 2008

If you are doing numeric sorts you can get a 2x speedup by using Math::GSL::Sort (part of Math::GSL), which also has functions like "find the k smallest" and "find the k largest".



Posted at 10:57pm on Wednesday, October 22nd, 2008

i have one big file contain data like
Term0|Term2: 0000023|0000103 0044237 2 0.463338365057
Term0|Term3: 0000023|0000105 0044238 2 0.422143662
Term0|Term4: 0000023|0000154 0044238 2 0.422143662
Term0|Term5: 0000023|0000160 0008150 0 1.0
Term0|Term6: 0000023|0000162 0044238 2 0.422143662
Term0|Term8: 0000023|0000256 0044237 2 0.463338365057
Term0|Term9: 0000023|0000270 0005975 3 0.0445726374991
Term0|Term10: 0000023|0000271 0005975 3 0.0445726374991
Term0|Term11: 0000023|0000272 0005975 3 0.0445726374991
Term0|Term12: 0000023|0000746 0008150 0 1.0
Term0|Term13: 0000023|0000902 0008150 0 1.0
Term0|Term14: 0000023|0000917 0008150 0 1.0
Term0|Term15: 0000023|0000918 0008150 0 1.0
Term0|Term16: 0000023|0001514 0044238 2 0.422143662
Term0|Term17: 0000023|0001522 0044238 2 0.422143662
Term0|Term18: 0000023|0001539 0008150 0 1.0

I wants to extract the values in between 0 to 0.05
The value meens the last Column value....

frinz rodney   

Posted at 9:50pm on Wednesday, November 12th, 2008

hi!!!!!!!!!!!!!!!!!!!!!!!good job..............
thnkz 4 ur comcrn


Posted at 2:39pm on Thursday, November 20th, 2008



Posted at 5:54pm on Thursday, December 11th, 2008

thanks for really nice article!
i m facing a little prblem now. pls kindly help me.
i want to sort list which contanins lists as folows



@list2 = sort customerSortByName (@mainArray);

pls kindly reply me how can i sort this?

thanks again..


Posted at 10:51am on Monday, January 5th, 2009

OK, how about this one:

I have a %hash where the keys are strings, and the values are integers. I want to turn this into a sorted @list based on the integer values stored in %hash, largest to smallest.

${"key1"} = 1;
${"key2"} = 2;
${"key3"} = 3;
${"keyN"} = N;

The integer values are conveniently chosen in the example for illustration purposes only. Any valid integer could be stored in any location of %hash;

sorting should yield the following:

$list[0] = N;
$list[1] = N-1;
$list[2] = N-2;
$list[N-1] = 1;

I'm sure this is probably easy, but it's my first day back on the job since the holidays, so my head is still elsewhere. :-)

Thanks for the help!


Posted at 11:08am on Monday, January 5th, 2009

sort {$b <=> $a} values %hash; should do it.


Posted at 11:18am on Monday, January 5th, 2009

Oops! The sorted result actually needs to contain the keys (not the stored integers), and so should look like the following:

$list[0] = "keyN";
$list[N-3] = "key3";
$list[N-2] = "key2";
$list[N-1] = "key1";

The result doesn't need to be a @list. Another %hash is OK, as long as the keys in the new %hash are (obviously) unique and easily sorted, such as integers (but not the stored integers of the original hash, as they are not necessarily unique):

$hash2{0} = "keyN";
$hash2{N-3} = "key3";
$hash2{N-2} = "key2";
$hash2{N-1} = "key1";

Sorry for mis-stating the desired result of the original problem.


Posted at 11:22am on Monday, January 5th, 2009

So you want to sort the keys of the hash in decreasing value order:

sort {$hash{$b} <=> $hash{$a}} keys %hash;


Posted at 4:15pm on Monday, January 5th, 2009

I'm sorry. I'm not stating the problem clearly enough.

I'm going to use a very concrete example instead of trying to state the problem in the abstract.

Suppose I go to the zoo and count the animals. The keys for %hash are the animal names, and the values stored in %hash are the counts for each type of animal:

$hash{"monkey"} = 12
$hash{"duck"} = 3
$hash{"horse"} = 9
$hash{"pig"} = 27
$hash{"alligator"} = 9

I want to output the animal names based on the number of animals I counted of each type, ranked most to least:

$list[0] = "pig"; # 27
$list[1] = "monkey"; # 12
$list[2] = "horse"; # 9
$list[3] = "alligator"; # 9
$list[4] = "duck"; # 3

The "horse" and "alligator" entries may be swapped and still yield a valid result, as they both have an assigned count of 9.

Hope this is more clear. Sorry for the confusion.


Posted at 6:32pm on Monday, January 5th, 2009

Look at my previous response. It should so exactly what you want, ie, return a list of animals ordered by decreasing count.


Posted at 6:53pm on Tuesday, January 6th, 2009

Thanks for putting the aardvark last. That example allowed me to resolve my problem.


Posted at 6:30am on Wednesday, January 14th, 2009

Wow...Natural sorting rocks for hash keys that are both text & numerical. I had this scenario and the keys were sorting like: 1,11,110,2,3,4,5,6,7,8,9 but with nsort, it fixed the problem chop chop.

use Sort::Natural;


foreach $key (nsort keys %hash)
print "KEY: $keyn";


KEY: mini-1
KEY: mini-2
KEY: mini-3
KEY: mini-4
KEY: mini-5
KEY: mini-6
KEY: mini-7
KEY: mini-8
KEY: mini-9
KEY: mini-10
KEY: mini-11
KEY: mini-110


Posted at 6:41am on Thursday, January 15th, 2009

lawson - why would you ever want such a thing? Just do it with a hash and sort with the technique you were taught above.


Posted at 10:09am on Tuesday, February 10th, 2009

Ahh, this is so much more simple then what i was going to do. I am wring an automation program that is based in XML which has made the programing that much harder due to the levels. I needed to sort systems based off their current load (servers under test relying on them for performance). To give a basic example of what i am doing and as my prof of concept:

use XML::Simple;

my $g_systems = {};
$g_systems->{systems}->[0]->{linux}->[0]->{ipaddress} = "1";
$g_systems->{systems}->[0]->{linux}->[0]->{nodes} = "0";
$g_systems->{systems}->[0]->{linux}->[1]->{ipaddress} = "2";
$g_systems->{systems}->[0]->{linux}->[1]->{nodes} = "2";
$g_systems->{systems}->[0]->{linux}->[2]->{ipaddress} = "3";
$g_systems->{systems}->[0]->{linux}->[2]->{nodes} = "1";
$g_systems->{systems}->[0]->{linux}->[3]->{ipaddress} = "4";
$g_systems->{systems}->[0]->{linux}->[3]->{nodes} = "0";

my $ys = new XML::Simple (keeproot => 1, forcearray => 1);
my $testXML = $ys->XMLout($g_systems);
print $testXML;

@{$g_systems->{systems}->[0]->{linux}} = sort {$a->{nodes} $b->{nodes}} @{$g_systems->{systems}->[0]->{linux}};

my $testXML = $ys->XMLout($g_systems);
print $testXML;



Posted at 6:40am on Friday, March 13th, 2009

Many thanks, this solved my problem.


Posted at 6:05pm on Wednesday, April 1st, 2009

Wonderful article, thanks a lot.


Posted at 9:01am on Friday, April 3rd, 2009

Thanks dude..
Neatly explained..


Posted at 8:27am on Tuesday, April 7th, 2009

Great website, I have something semi related to this, topic. Can anyone show me how to solve this problem?
If you can please email me ( I greatly appreciate any help with this. I am a perl infant, who needs help. Thank you in advance for any help.
I have a data file with 2 columns :the 1st col is a group name (example 'aaa' 'bbb' this column can remain untouched) the 2nd col has X,Y values. I need to sort all values within each group name by X value ascending . Then for each Common Value of X sort the Y values. Here's the catch each time a new value of X is present the order of the Yvalue sort needs to toggle between ascending & decending sort or (normal /reverse) sorting, which ever is the proper terminology.
Starting Format
data file
'aaa' 1,2
'aaa' 2,1
'aaa' 2,3
'aaa' 4,1
'aaa' 3,2
'aaa' 3,1
'aaa' 4,5
'bbb' 2,2
'bbb' 2,5
'bbb' 2,1
'bbb' 4,3
'bbb' 4,6
'bbb' 4,1
'bbb' 4,2
'ccc' 3,3
'ccc' 3,6
'ccc' 1,3
'ccc' 1,1
'ccc' 6,4
'ccc' 6,6
'ccc' 2,2
'ccc' 2,4

for each new X value, within each col 1 group
Resulting File has X's sorted and toggles Y sort
'aaa' 1,2
'aaa' 2,3
'aaa' 2,1
'aaa' 3,1
'aaa' 3,2
'aaa' 4,1
'aaa' 4,5
'bbb' 2,1
'bbb' 2,2
'bbb' 2,5
'bbb' 4,6
'bbb' 4,3
'bbb' 4,2
'bbb' 4,1
'ccc' 1,1
'ccc' 1,3
'ccc' 2,4
'ccc' 2,2
'ccc' 3,3
'ccc' 3,6
'ccc' 6,6
'ccc' 6,4


Posted at 8:32am on Tuesday, April 7th, 2009

I just wanted to add that there are spaces between the Group name and the X,Y values that didnt post properly when I clicked [Add comments]
'aaa' spaces 1,1


Posted at 12:28pm on Tuesday, April 21st, 2009


i acutlay needed something like this where i was sorting a list that contained data that fit a format but also some datat that did not fit that format, i wanted all the data taht did not fit the format to come last


Posted at 1:28pm on Thursday, April 23rd, 2009

i have file like below format (abc.efg.mmddyy123456.tar.gz)


Can anyone help me to sort.


Posted at 2:12am on Thursday, May 28th, 2009

Use the CPAN module Sort::Naturally, it has proven to be extremely useful for these cases!!   

Posted at 7:43pm on Thursday, June 11th, 2009

hey can anyone help me sort characters ???
is it possible?


Posted at 6:32pm on Saturday, June 13th, 2009



Posted at 11:13pm on Thursday, June 18th, 2009

Very gud and neat explanation of Sorting in perl............


Posted at 2:18am on Tuesday, June 30th, 2009

Best natural sort subroutine ever!! It can even handle negative numbers (thanks to Tye from Perl Monks):

my @array=(-2kjh, lkjlk, 346k, 45, -54, 65kjl, kjd67);
#call sub
@array=@{mynatsort (@array)};

sub mynatsort{
#CASE-SENSITIVE-->ordena antes 12B que 12a, por ejemplo

my ($array_ref)=@_;

my @deltas=@$array_ref;

@deltas= do {
my( @sort, %sort )= map {
local($_)= $_;
my $sign= s#^([-+]?)## && $1;
s#(d+)# "x80" ^ pack"N",$sign.$1 #ge;
} @deltas;
@sort{@sort}= @deltas;
@sort{ sort @sort };

return (@deltas);


Posted at 2:20am on Tuesday, June 30th, 2009

call it by reference with "@array"


Posted at 12:05pm on Tuesday, August 4th, 2009

linux/perl newbie & i confused...
the code i enter:

#!/usr/bin/env perl
use strict;
use warnings;
my @unsorted = (1, 2, 11, 24, 3, 36, 40, 4);
my @number = sort { a$ b$ } @unsorted;
print "Numeric sort: @numbern";

the error message i get when i run program:

Possible unintended interpolation of @number in string at line 6
Global symbol "@number" requires explicit package name at line 6
Missing right curly or square bracket at line 7, at end of line
syntax error at line 7 EOF
Execution of aborted due to compilation errors

what i do wrong?


Posted at 8:13am on Wednesday, August 19th, 2009

cool one


Posted at 9:03am on Wednesday, August 19th, 2009

it's the best. Thanks man


Posted at 1:50pm on Wednesday, September 2nd, 2009

Daniel from 2007 - 2 years later your sort by hash of hash value saved me. Thanks for posting - I was wondering how to do that!


Posted at 3:42am on Thursday, September 3rd, 2009

"Get an alphabetical sort of words, but make 'aardvark' always come last."

ends my 2 days battle !!

Thanks !


Posted at 12:46pm on Sunday, September 27th, 2009

hi uuuuuuuuuuu jjjjjjjjj

Titus Abraham   

Posted at 11:53pm on Friday, October 2nd, 2009

Thanks a ton for the concise and precise data ..,

Priyank Ganadhi   

Posted at 3:08pm on Sunday, October 11th, 2009

Great article.


Posted at 12:10pm on Wednesday, October 14th, 2009

Thanks, spot on and very helpful


Posted at 9:28am on Wednesday, November 4th, 2009

You can also use the comparison block to compare two elements at once:

Say, for example @not_sorted is a list of array references of length 2 and you want to sort on both elements in each array:

@sortedArrayRefs = sort { $a->[0] $b->[0] || $a->[1] $b->[1]] } @unsortedArrayRefs; # also mentioned in the perl cookbook, which I highly recomend


Posted at 6:45pm on Thursday, November 5th, 2009

Can someone show me how to use if statement to display two numbers entered by the user in ascending order. I'm new to perl Please help


Posted at 3:53am on Friday, December 25th, 2009

Warm Hand,benefit will mass introduce season religion lawyer necessary publication tend purpose central desire wash exchange point meaning pick please range average parent train payment additional clothes for gas meaning piece problem benefit typical doubt star work good kill significance threaten organise manager fit mother data record less beginning mother woman excellent establish now widely sure contribute type incident once chief concentration realize price available citizen order along challenge press you work yesterday to conflict hole expense constant distance somewhat avoid gun immediately observe although properly


Posted at 6:48am on Monday, January 4th, 2010

It's helpful to me! Thanks!


Posted at 6:59am on Monday, January 11th, 2010

How does using ba @notSorted sorts in revirse order .
whether you use ab or ba , which ever is greated will come first


Posted at 3:17am on Wednesday, January 20th, 2010

very helpful


Posted at 3:55am on Saturday, January 23rd, 2010

I am having one file like this:



I want the output in this format:
using perl language how to solve this problem

Vikram Pampati   

Posted at 4:55pm on Tuesday, February 16th, 2010

Simple to use.

Have a question.
How to sort hash keys (not by value but the keys). I am currently assigning keys to an array and then sorting the array. Wanted to check if there is a better way.

Varun Kumar Goswami   

Posted at 5:09am on Friday, February 26th, 2010

I have one array that contains the date as string,now how to short these array element.


Posted at 1:38pm on Friday, February 26th, 2010

Vikram, to sort keys you could do:

sort { $a $b } keys %hash


Posted at 9:01pm on Thursday, March 18th, 2010

Exactly what I was looking for, thanks :)


Posted at 5:18pm on Sunday, March 21st, 2010

I have a list of values (traffic data) like: 56.2 mb, 0.7 gb, 45.0 kb. Is it possible to sort this list according to the amount of traffic? That is, first sorting by unit and then by numeric value?


Posted at 1:28am on Tuesday, March 30th, 2010



Posted at 8:29am on Friday, May 7th, 2010

nice one..

Ahsan Abdul Jabbar   

Posted at 11:38pm on Wednesday, May 12th, 2010

Extremely nice topic...!


Posted at 12:51am on Thursday, May 20th, 2010

good enough


Posted at 4:35am on Thursday, May 27th, 2010

spot on! thanks mate


Posted at 1:51pm on Monday, July 12th, 2010

Best explanation of perl sort ever!!! Thanks a bunch!!!


Posted at 2:35am on Wednesday, August 4th, 2010

thanks for the info buddy ... I was searching for numerical sort and got it here ...


Posted at 5:37pm on Sunday, August 8th, 2010

hi i was wondering how to sort names alphebetically from a file because im not sure how to sort the names alphebetical at my variable name $model, i was wondering if anyone could help me on this?

$total=0; #set total to 0
$continue=0; #set continue to 0

open(FILE, ">list_of_cars.htm"); # tell program to open file

print FILE "n";
print FILE "n"; # write HTML information to sc reen
print FILE "Cars Details n";
print FILE "n";
print FILE "n";
print FILE "n";
print FILE " Below are a list of detailed cars:n";
print FILE "n";
print FILE " n";
print FILE " Modeln";
print FILE " Manufacturern";
print FILE " Engine Sizen";
print FILE " Top Speedn";
print FILE " Price (£)n";
print FILE " n";

do{ #initialise a do loop
print "Enter a model of the car : "; #ask user to enter Enter a model of the car
$model=; #store as $model
chomp$model; #chomp $model

print "enter the manufacturer of the car : ";

print "enter the engine size: ";

print "enter the top speed of the car: ";

print "enter a cost of the car: £";

print FILE " n"; # print car details in the HTML file
print FILE " $modeln";
print FILE " $manun";
print FILE " $sizen";
print FILE " $speedn";
print FILE " $costn";
print FILE " n";

$total=$total+$cost; #adding the cost to the previous total

print"Do you want to enter another car?n"; #Ask user if they wish to continue
print"Enter 1 to continue adding else enter 0 if to finish : "; #Tell user what to enter
$continue=; #store user input as continue
} until ($continue==0); #end do loop

print FILE "n";
if ($continue==0) { #do above while $continue is not 0

print FILE "The total cost of your cars is: £ $totaln"; #print the total to the html file


print FILE "n";
print FILE "n";
print FILE "n";

close FILE;



Posted at 5:45pm on Sunday, August 8th, 2010

sorry , dont know why it wasnt showing the tags. if you could kindly post me your email address i could send you my code. im having a hard time sorting this one out. Thanks. my email is


Posted at 5:48pm on Sunday, August 8th, 2010

$model=; .... was suppose to be $model; # to get user input

Sang Beom, Park   

Posted at 11:58am on Saturday, August 21st, 2010

Thaks very much. ^^;

Seoul, Korea.

AC Needs Help   

Posted at 1:21pm on Friday, September 10th, 2010

I am new to Perl and I have data in a file that I want to sort uniquely on the fourth column (will keep first occurrence) but have not been able to figure out how to do it. I'm sure I need to use a hash but not quite sure how. Any help would be greatly appreciated. Here is the data:

20100908 1145:16.874 PCCONF2 mcppb602 PCID> MCPP2
20100908 1145:17.778 PCCONF2 sdpsb601 PCID> SDPSA
20100908 1145:21.201 PCCONF2 mcppb601 PCID> MCPP1
20100908 1145:29.805 PCCONF2 fdpsb601 PCID> FDPSA
20100908 1146:17.972 PCCONF2 cwpb602 PCID> CWP2
20100908 1147:01.928 PCCONF2 cwpb609 PCID> CWP7
20100908 1147:01.972 PCCONF2 cwpb603 PCID> CWP4
20100908 1147:02.035 PCCONF2 mcppb602 PCID> MCPP2
20100908 1147:02.088 PCCONF2 sdpsb601 PCID> SDPSA
20100908 1147:02.327 PCCONF2 mcppb601 PCID> MCPP1
20100908 1147:10.590 PCCONF2 fdpsb601 PCID> FDPSA
20100908 1147:10.646 PCCONF2 mcppb602 PCID> MCPP2
20100908 1147:10.690 PCCONF2 sdpsb601 PCID> SDPSA


Posted at 6:58pm on Saturday, September 18th, 2010

According to my own monitoring, billions of persons in the world receive the mortgage loans from good banks. Hence, there is a good chance to find a sba loan in all countries.


Posted at 2:40am on Friday, October 22nd, 2010

Every one admits that today's life is not cheap, nevertheless people require cash for different stuff and not every man gets big sums cash. Thus to receive some personal loans and just credit loan would be a proper way out.


Posted at 9:15pm on Friday, October 22nd, 2010

This is well known that money makes people disembarrass. But how to act if somebody doesn't have cash? The one way is to receive the personal loans or car loan.


Posted at 1:12am on Wednesday, November 17th, 2010

You might want to have 'aardvark' last, from a Scandinavian perspective. You see, 'aa' is equivalent to the letter 'å', which is the last letter of the Scandinavian alphabets. So this is a very real problem, and a useful solution :)


Posted at 4:17am on Monday, January 31st, 2011

it's good article.Thanks..


Posted at 4:18am on Monday, January 31st, 2011

it's good article.Thanks..


Posted at 2:28pm on Saturday, February 12th, 2011

Good one man...


Posted at 4:54pm on Tuesday, February 15th, 2011

very nice work

Lalit Mohan   

Posted at 11:31pm on Monday, February 21st, 2011

For any perl problems and solutions, visit at


Posted at 1:07am on Tuesday, February 22nd, 2011



Posted at 4:54pm on Monday, March 7th, 2011

Thank you very much,

Your last example (Now, why you would want to do that is another question...), was extremely useful.

I was trying to sort a bunch of products, firstly by whether they are in stock or out of stock, then by alphabetical order!



Posted at 1:59am on Wednesday, May 4th, 2011

For any perl problems and solutions,visit at
Ghd Straighteners
GHD Black


Posted at 2:02am on Wednesday, May 4th, 2011

For any perl problems and solutions,visit at
Ghd Straighteners
GHD Black

Alex De Los Santos   

Posted at 8:04am on Tuesday, June 7th, 2011

Good Afternoon,

My name is Alex De Los Santos and I work at LinkVehicle. I reviewed your website and wanted to speak to you about becoming a publisher in our marketplace. We sell Text-Link-Ads on our publisher websites (these are Static HTML links). We allow our publishers to place ads manually or by installing our PHP server side script. Our ads are normally placed in the headers, sidebars, or footers of websites. We split the cost of each ad placed on our publisher websites 50/50 and bill our advertisers on a recurring monthly basis. This means you’ll receive a check from us via PayPal on the 1st of every month! If you are interested in making additional money by placing Text-Link-Ads on your website(s). Please, sign up at LinkVehicle and submit your website(s). I would be very happy to put together a spreadsheet that shows you how much you can expect to earn from your website(s). If interested in this make sure to reply with the exact URL’s. FYI, we have a large team of SEO professionals that work around the clock to sell ads on your website(s). You have nothing to lose but a nice monthly check if you don’t sign up!


Alex De Los Santos
Senior Account Executive
P (203) 793-7243
AIM: DeLo2835


Posted at 3:17am on Wednesday, June 8th, 2011

Straight to the point... bingo... thanks for the article..


Posted at 1:57am on Monday, June 20th, 2011


I now have an issue when the array elements are alphanumerical. For example the my sorted array now looks like,


How to sort it so that A1B22 comes at the last (or at the appropriate place where it is intended to be)


Posted at 5:07am on Thursday, July 7th, 2011

I love this page !!


Posted at 7:45am on Tuesday, July 12th, 2011

flintstones{husband} = "fred",
flintstones{pal} = "barney",
jetsons{husband} = "george"
jetsons{wife} = "jane"
jetsons{his boy} = "elroy"
simpsons{husband = "homer"
simpsons{wife} = "marge"
simpsons{kid} = "bart"

This is my hash, i need to sort based on the value. I need an out put like below.

flintstones{pal} = "barney",
simpsons{kid} = "bart"
jetsons{his boy} = "elroy"
flintstones{husband} = "fred",
jetsons{husband} = "george"
simpsons{husband = "homer"
jetsons{wife} = "jane"
simpsons{wife} = "marge"

Any body help me


Posted at 8:43pm on Friday, September 2nd, 2011

nice thax>!


Posted at 1:19am on Thursday, September 22nd, 2011

Thank you so much! I didn't know $a and $b are special variables and kept declaring my own "my ($a, $b);" which was giving me errors. After reading this, I deleted the variables that I had declared and the sort worked! Thanks!!!


Posted at 11:40pm on Saturday, October 8th, 2011

I will recommend not to hold off until you get big sum of cash to buy all you need! You can just get the home loans or student loan and feel yourself comfortable


Posted at 2:32pm on Tuesday, October 11th, 2011

Every body remembers that modern life seems to be expensive, nevertheless some people need cash for various things and not every one earns enough cash. Hence to get good loan and short term loan will be a correct solution.


Posted at 11:39am on Thursday, October 20th, 2011

do you have to use a and b or can you use other letters and or variables?

Edward Petersen   

Posted at 4:16pm on Tuesday, October 25th, 2011

Oddly enough ... I needed aardvark last. I had a hash where the values were arrays of regex values, but one of the values of one of my keys could trump the values of another. So it was really helpful to stick that one last. Thanks!


Posted at 9:30am on Monday, October 31st, 2011

For IP order sort:

foreach $ip ( sort {
@ip_a = split( /./, $a ) ;
@ip_b = split( /./, $b ) ;

if ( $ip_a[0] != $ip_b[0] ) { return $ip_a[0] $ip_b[0] }
if ( $ip_a[1] != $ip_b[1] ) { return $ip_a[1] $ip_b[1] }
if ( $ip_a[2] != $ip_b[2] ) { return $ip_a[2] $ip_b[2] }
return $ip_a[3] $ip_b[3] ;

} ( keys %ip_list ) )
print "$ipt$ip_list{$ip}n" ;


Posted at 9:36am on Monday, October 31st, 2011

Above does not preserve the code :-( so the compare operator and indenting disappears...

photo recovery software   

Posted at 1:52am on Friday, November 4th, 2011

Great article; Very nice content; techniques are really fabulous and quick result oriented.
photo recovery software


Posted at 5:39am on Monday, December 12th, 2011

Pls am new to perl
How can I sort words backward
(e.g., caT, doG, moneY, peN...sorted from the last letter as

Please help thanks


Posted at 8:07pm on Wednesday, December 14th, 2011

Thank you for such a concise and clear solution. First page I checked too,


Posted at 4:03am on Tuesday, January 3rd, 2012

Abschmuecken solar werden scherzen lichtundurchlaessig Hybridauto best web hosting vier demoliert niederzumetzeln verzweigen offensichtlich Macabeo werden ihm fuenfzehn selbst abwerfen aeu�erst und werden billig mongolische Sprache siebzehn, betroffen dingfest einsperren denjenigen euch einstallen sechse, Jagdhund auszubessern aufoktroyieren Was sich liebt, das neckt sich werden.


Posted at 5:22am on Monday, February 20th, 2012

this is for sort an array which is given please upload example for string getting as input and sort it


Posted at 5:22am on Monday, February 20th, 2012

this is for sort an array which is given please upload example for string getting as input and sort it


Posted at 2:43am on Thursday, March 1st, 2012

can you please provide me the syntax for a command that sorts an array numerically and ignores all the duplicate ones, so that the sorted array has all the unique values...


Posted at 10:24pm on Friday, March 16th, 2012

I'm trying to do the same type of thing as 'Matt - Posted at 6:43am on Thursday, January 31st, 2008'
but that suggestion doesn't appear to work.
Eg: scalar ref to hash of nested hashes & want to sort by first key in each (last) hash.
A rough example...need to sort by 'fname' values, eg: apple, banana, orange.

my $a_ref = {
'myfruit' => {
'myfruit_01' => {
'fname' => 'banana',
'cals' => 5,
'fat' => 2,
'myfruit_02' => {
'fname' => 'apple',
'cals' => 3,
'fat' => 1,
'myfruit_03' => {
'fname' => 'orange',
'cals' => 7,
'fat' => 3,

my ($k1, $k2),
for $k1 (keys %{$a_ref}) {
for $k2 (keys %{$a_ref->{$k1}}) {
print "Fruit Name = $a_ref->{$k1}->{$k2}->{fname}n"; #sort by these values
print "Calories = $a_ref->{$k1}->{$k2}->{cals}n";
print "Fat = $a_ref->{$k1}->{$k2}->{fat}n";

Tried many versions of the 2nd (inner) for loop, to no avail... including:

for $k2 (sort {{$a}->{fname} cmp {$b}->{fname}} keys %{$a_ref->{$k1}}) {
for $k2 (sort {{$a}->[0] cmp {$b}->[0]} keys %{$a_ref->{$k1}}) {

Still googling for a solution...


Posted at 10:48pm on Friday, March 16th, 2012

Per my last post... figured it out (finally LOL) :)

The 2nd (inner) loop should be:

foreach $k2 (sort {$a_ref->{$a}->{fname} cmp $a_ref->{$b}->{fname}} keys %{$a_ref->{$k1}}) {


Posted at 11:22pm on Thursday, April 12th, 2012

why we use ls in sorting

Hugh Betcha   

Posted at 10:24am on Friday, April 13th, 2012

The aardvark example is actually exactly what I was looking for. Someone set an id to 99 in a list assuming it would always be the highest value and sort last in a list, but then over time entries were added to the list in excess of 99. Now I need to force 99 to be the last id in a sorted list. Thanks.


Posted at 6:27am on Friday, May 25th, 2012

Excellent. Makes it easy even for numpties like me. Got it working in 5 mins. Thanks.


Posted at 2:32pm on Friday, June 1st, 2012

Good Post


Posted at 10:00am on Wednesday, June 20th, 2012

The aardvark code was very useful to me. Thanks!


Posted at 9:26pm on Friday, July 27th, 2012



Posted at 9:26pm on Friday, July 27th, 2012



Posted at 3:16am on Tuesday, August 21st, 2012

Try cannabis stpirs, they can be put in your son's mouth and will disolve before he has a chance to spit it out. Just a thought. And arm yourself with good research and bring it to a good doctor who sees your videos of your son harming himself. Get an MRI of brain to rule out anything hurting him. You have been through so much may God give you and your son peace, healing and hope and may you find the right treatments to help this precious child.


Posted at 9:21pm on Tuesday, August 21st, 2012

nwK92d ffdsgmwgarjo


Posted at 1:35pm on Thursday, August 23rd, 2012

How does one sort a list of files by extension alphabetically?


Posted at 3:54am on Friday, August 24th, 2012

bZnIAW vvbozeulzfpt

Lester Pascua   

Posted at 9:34pm on Thursday, August 30th, 2012

cab you help pe..

Word Sorter
enter word1 : lumboy
enter word1 : apple
enter word1 : grapes
enter word1 : chesa
enter word1 : manga

OUTPUT : apple Chesa grapes lumboy mangaa


Posted at 6:32am on Saturday, September 8th, 2012

if you already use $a $b in your program, {$a $b} throws up errors on you. Any other way of sorting elements numerically in Perl?


Posted at 10:43pm on Wednesday, September 12th, 2012



Posted at 5:19pm on Monday, November 19th, 2012

Big help, nice clean example. TY


Posted at 11:00am on Sunday, October 27th, 2013

yonqxqfsmgfdu, pidstfpkzc


Posted at 8:35am on Monday, October 28th, 2013

uwrbxqfsmgfdu, kofcilugal


Posted at 8:23am on Monday, November 25th, 2013

Cant find anywhere a routine to sort an AoA from high to low for the row values but alternating low to high and high to low for the columns e.g.


Any ideas?


Posted at 8:26am on Monday, November 25th, 2013

Cant find anywhere a routine to sort an AoA from high to low for the row values but alternating low to high and high to low for the columns e.g.


Any ideas?


Posted at 11:31pm on Sunday, February 2nd, 2014


Dr Benson   

Posted at 10:29am on Monday, May 5th, 2014

Do you need a loan apply now via for more information okay.Dr. Benson loan finance companiesCEO ... / MD


Posted at 5:53pm on Thursday, May 29th, 2014

Great article, I found the lc alphabetical sort very handy.


Posted at 8:30am on Wednesday, July 23rd, 2014

"Get an alphabetical sort of words, but make 'aardvark' always come last."

Perfect that is exactly what I wanted to do! Well maybe not exactly but perfect example. I want rootvg output to always come first when outputting VG information in a report with the rest in alphabetical order.

sweta sengar   

Posted at 3:37am on Thursday, November 27th, 2014



Posted at 5:37pm on Tuesday, December 9th, 2014



Posted at 2:15pm on Friday, May 1st, 2015

how to sort array by 1st letter amd then by length of the string.
Eg:baaaal,bo,addree,azer should be
azer,addree,bo,baaaal after sort

Comments to date: 186.

Like it? Share it!

  Post to
Post to

Hosted Perlfect Search(beta)

Don't have the time or the expertise to install and maintain Perlfect Search? Then our freehosted Pelrfect Search service is for you!

Suggested Reading

Effective Perl Programming Effective Perl Programming is a thoroughly involved and enjoyable book about perl programming. This book does not merely show you how to get your job done, but also shows you effective and elegant solutions to perl programming problems. Effective perl programming is not a manual. It is a book about good programming in the mindset of the perl language. If you like perl and you enjoy programming then you are sure to like this book.

The Regex Tutor

Try your regular expressions online with the regex tutor.