Help with sorting lists of lists

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

    I apologize if this is the wrong place to post this; please let me know
the proper target if so.

    I have a list of lists of numbers, and I want to sort the sublists.
Every variant on the syntax that I've tried either doesn't visibly do
anything to sort the lists, or else undefines them all. Here's what I
originally tried:

    for (my $i = 0; $i < $numActors; ++$i)
        for (my $j = 0; $j < $actors[$i]; ++$j)
            $prolls[$i][$j] = int (rand(20) + 1);
}        }
        @prolls[$i] = sort {$a <=> $b} @prolls[$i];
}    }

    I suspect that I'm getting tripped up by how Perl handles lists of
lists and references and all that, but all the searching I've done
hasn't turned up anything that's worked. Any help would be appreciated.

    For reference, I'm working on a dice rolling program for the Donjon
tabletop RPG. It's a great system, but it needs a lot of d20s...

"Don't take life so serious, son - it ain't nohow permanent." -

Re: Help with sorting lists of lists

Quoted text here. Click to load it

Life is generally easier without C-style loops.

Quoted text here. Click to load it

You should

use strict;


use warnings;

What you probably want to do is set the $i th element of @prolls to a
reference to the sorted array: i.e. (untested)

$prolls[$i] = [ sort { $a <=> $b } @{ $prolls[$i] } ];

Since you did not post a self-contained script that I could run (why not?),
I am not sure this would solve your problem. Take a look at

perldoc perlreftut

#! perl

use strict;
use warnings;

my @lol = (
    [ 3, 7, 4, 5 ],
    [ 11, 15, 1, 3, 5 ],
    [ 2, 1, -1, 3, 4, 5, 9, 22, 11 ],

for (@lol) {
    $_= [ sort {$a <=> $b} @{ $_ } ];

use Data::Dumper;
print Dumper \@lol;


Site Timeline