Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Grace be with you, brethren

I have two newbie questions regarding LOLs.

If I have a list of lists, such as @LOL={{1,2,3},{4,5,6},{2,3,4}}, how do I look up, say, the second element in the second list?
Can I do  $variable=$$LOL[2][2]?

My other question is how to I sort the lists according to the first element in each list?

Any help will be much appreciated.

Thanks,

C

Replies are listed 'Best First'.
Re: list of lists (LOL)
by davido (Cardinal) on May 05, 2004 at 18:46 UTC
    As has already been pointed out, your notation is a little off... In Perl, {} brackets usually pertain to blocks, anonymous hash refs, dereferencing of references, or quantifiers in regexps. Your notation should be [[1,2,3],[4,5,6],[2,3,4]].

    Note that if you have code that looks like:

    my @array = [[1,2,3],[4,5,6],[7,8,9]];
    You're actually creating an array whos first element is a reference to the datastructure. It is more appropriate to do one of the two following things:

    my @array = ([1,2,3],[4,5,6],[7,8,9]); # Note parens. # or my $aRef = [[1,2,3],[4,5,6],[7,8,9]]; # Note aref, not array

    In any respect, you can dereference a LoL (or AoA technically) as follows:

    ${$aRef->[0]}[1] # or $aRef->[0]->[1] # or the most common... $aRef->[0][1]
    There's a great little cheat-sheet that tye put together called References quick reference. Check it out! :)

    You can also get a lot of good information out of perllol.


    Dave

Re: list of lists (LOL)
by geekgrrl (Pilgrim) on May 05, 2004 at 18:37 UTC
    actually you have hash references there. You want the structure to look like: [[1,2,3],[4,5,6],[2,3,4]] to be a list of a list.

    To retrieve the second element in the second list, you can access it like this: question 1:
    $var = $LOL->[1][1];


    Arrays start with 0 for the first element, 1 for the second, and so on.
Re: list of lists (LOL)
by nevyn (Monk) on May 05, 2004 at 18:46 UTC

    The easiest way to see what is going on here is to use Data::Dumper; ...

    use Data::Dumper; @a = {{1, 2, 3}, {4, 5, 6}, {2, 4, 8}}; @b = ((1, 2, 3), (4, 5, 6), (2, 4, 8)); $a = [[1, 2, 3], [4, 5, 6], [2, 4, 8]]; print Dumper(\@a); print Dumper(\@b); print Dumper($a);

    Seeing the output, it should be more obvious that you need to do something like...

    $a = [[1, 2, 3], [4, 5, 6], [2, 4, 8]]; @$a = sort { $a->[0] <=> $b->[0] } @$a;
    --
    James Antill
Re: list of lists (LOL)
by geekgrrl (Pilgrim) on May 05, 2004 at 18:46 UTC
    #2: my @sorted = sort {$a->[0] <=> $b->[0]} @{$lol};