Mandor has asked for the wisdom of the Perl Monks concerning the following question:
Interestingly I found out that this wasn't working.use strict; my $list = undef; my $lastnode = \$list; while (1) { print '<i>nput, <o>utput : '; chomp (my $input = <STDIN>); if ($input eq 'i') { ($list, $lastnode) = add ($list, $lastnode); next; } if ($input eq 'o') { show ($list); next; } } sub add { my ($list, $lastnode) = @_; chomp (my $input = <STDIN>); my $newnode = [undef, $input]; $$lastnode = $newnode; $lastnode = \$newnode -> [0]; return ($list, $lastnode); } sub show { my $list = shift; for (my $node = $list; $node; $node = $node -> [0]) { print $node -> [1] . "\n"; } }
$list wasn't being set, which kinda defeated it's purpose.$$lastnode = $newnode;
I removed the variable passing and accessed $list and $lastnode directly.use strict; my $list = undef; my $lastnode = \$list; while (1) { print '<i>nput, <o>utput : '; chomp (my $input = <STDIN>); if ($input eq 'i') { &add; next; } if ($input eq 'o') { &show; next; } } sub add { chomp (my $input = <STDIN>); my $newnode = [undef, $input]; $$lastnode = $newnode; $lastnode = \$newnode -> [0]; } sub show { for (my $node = $list; $node; $node = $node -> [0]) { print $node -> [1] . "\n"; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(tye)Re: Linked List Strangeness
by tye (Sage) on Jan 31, 2002 at 17:55 UTC |