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

I'm sorry, don't hate me for asking this question, but is there any method of doing link list is Perl. Just a plain generica link list. Nothing complex. Just want to link on object to the next, but allow them to have multiple branches.

I am the first overweight, very tall munchkin... be very amazed.

Replies are listed 'Best First'.
Re: link list trouble
by fundflow (Chaplain) on Nov 17, 2000 at 21:26 UTC
Re: link list trouble
by clemburg (Curate) on Nov 17, 2000 at 21:18 UTC
Re: link list trouble
by japhy (Canon) on Nov 17, 2000 at 21:40 UTC
    Linked lists in Perl are far better implemented with a hash of all the elements -- it makes for much less memory, and allows you to cheat by accessing a point directly. I'll have some code up here in an hour or so to show it.

    The only problem is elements with the same value, but this (ah, yes) can be gotten around.

    japhy -- Perl Hacker and Regex Prince
      The interpreter mentioned in Lisp-In-Perl implements them as two arrays. One for all the 'car|down' nodes, and one for all the 'cdr|right' nodes. But then the nodes don't free themselves when they are no longer being referenced. A garbage collector has to periodically compact the arrays.

      Update: I did a rough benchmark of memory used by the two methods, and using array refs used ~3-4 times more memory. Is this because perl over-allocates whenever it allocates an array? Since you can pre-extend an array you know will be large, would it help if it were possible to pre-de-extend an array you know will be small? Here's the code I used (for comments on the fairness of the comparisons):
      my @arr; my @arr1; my @arr2; my $i=0; for (1..1_000_000) { # This #push @arr, [undef, undef]; # Or this push @arr, [++$i, ++$i]; # Vs. this: #push @arr1, undef; #push @arr2, undef; # Or this: #push @arr1, ++$i; #push @arr2, ++$i; } print "Done\n"; # Then just do a 'ps -lu runrig' at another command prompt when I get +here my $str=<STDIN>;
(jeffa) Re: link list trouble
by jeffa (Bishop) on Nov 17, 2000 at 21:19 UTC
    Well, if you really want to . . . check out Mastering Algorithms with Perl pages 47-72

    Jeff

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    F--F--F--F--F--F--F--F--
    (the triplet paradiddle)
    
Re: link list trouble
by runrig (Abbot) on Nov 17, 2000 at 21:34 UTC
    I put a lisp module on CPAN that imitates LISP-like linked lists and other functions in perl (its the one that still says 'blah blah blah'). Also see Lisp-In-Perl and More Lisp-In-Perl. It's still under construction, so some things may change.