Sort::Key::Natural will do the trick assuming you can use CPAN (see Yes, even you can use CPAN for tips on how), but there are a couple concepts here that are probably worth learning in any case:
sort lets you define a custom sort routine, like this:
use strict;
use warnings;
my @aChapters=("ch1","ch11","ch2","ch5","ch55","ch16");
my @aSorted = sort {
my ($sA, $iA) = ($a =~ /(^[^\d]+)(\d+)/);
my ($sB, $iB) = ($b =~ /(^[^\d]+)(\d+)/);
my $x = $sA cmp $sB;
($x = $iA <=> $iB) unless $x;
$x;
} @aChapters;
local $"="\n";
print "@aSorted";
$a and $b are special variables that represent the two members of the list you want to sort. The main trick here is to (i) split your name into two parts: an alpha part and a numeric part (ii) compare the alpha part using the alpha comparison operator (cmp) and the numeric part using the numeric comparison operator (<=>). See perlop for more information.
Best, beth
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|