Perl Monk, Perl Meditation PerlMonks

### comment on

 Need Help??
blazar's solution works properly, unlike some of the other solutions given above (++ for him), but mine is more efficient: 2.08 vs 3.68 seconds for 1000 iterations with 100 randomly generated items. Smaller sets show much the same ratio.
```use strict;
use warnings;

### Randomly generate numbers
my @array;
for (0..100) {
my @n;
push @n, (int rand 15) + 1;
for (0..((int rand 3) - 1)) {
push @n, int rand 15;
}
push @array, join '-', @n;
}

### Sort the numbers
my @arr = map { \$_ = join '-', @\$_ }
sort { mysort(\$a, \$b) }
map { \$_ = [split '-'] } @array;

print join "\n", @arr;

### mysort does the actual comparisons
sub mysort {
my (\$s1, \$s2) = (\$#{\$_[0]}, \$#{\$_[1]});
for (0..(\$s1 < \$s2 ? \$s2 : \$s1)) {
no warnings;
return \$_ if \$_ = \$_[0][\$_] <=> \$_[1][\$_];
}
### N comes before N-0
return (\$s1 < \$s2 ? -1 : (\$s2 > \$s1 ? 1 : 0));
}

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• 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 or How to display code and escape characters are good places to start.

Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2022-07-04 11:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?