Doing the naïve thing does the right thing, albeit with warnings:
use warnings;
use diagnostics;
use strict;
my @array = ("8.foo", "6.bar", "7.baz",
"5.biz", "3.fizzle", "0.fro", "9.boz");
print join "\n", sort {$a <=> $b} @array;
__END__
Argument "8.foo" isn't numeric in sort at 376443.pl line 6 (#1)
(W numeric) The indicated string was fed as an argument to an oper
+ator
that expected a numeric value instead. If you're fortunate the me
+ssage
will identify which operator was so unfortunate.
Argument "6.bar" isn't numeric in sort at 376443.pl line 6 (#1)
Argument "7.baz" isn't numeric in sort at 376443.pl line 6 (#1)
Argument "5.biz" isn't numeric in sort at 376443.pl line 6 (#1)
Argument "3.fizzle" isn't numeric in sort at 376443.pl line 6 (#1)
Argument "0.fro" isn't numeric in sort at 376443.pl line 6 (#1)
Argument "9.boz" isn't numeric in sort at 376443.pl line 6 (#1)
0.fro
3.fizzle
5.biz
6.baz
7.bar
8.foo
9.boz
However, if you want to dispense with the warnings, you could use the "Schwarzian Transform" like this:
use warnings;
use diagnostics;
use strict;
my @array = ("8.foo", "6.bar", "7.baz",
"5.biz", "3.fizzle", "0.fro", "9.boz");
print join "\n",
map {$_->[0]}
sort {$a->[1] <=> $b->[1]}
map { [$_, by_number($_)] } @array;
sub by_number {
my $value = shift;
if ($value =~ m/^(\d+)/) {
return $1
}
}
-
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.