Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

(tye)Re: Linked List Strangeness

by tye (Sage)
on Jan 31, 2002 at 17:55 UTC ( [id://142469]=note: print w/replies, xml ) Need Help??


in reply to Linked List Strangeness

Let me make a tiny change so that I can talk about this more easily. The problem is that one $list is being changed while the other $list isn't. So lets rename one of them:

use strict; my $list = { head=>undef, tail=>undef }; while (1) { print '<i>nput, <o>utput : '; chomp (my $input = <STDIN>); if ($input eq 'i') { add($list); next; } if ($input eq 'o') { show($list); next; } } sub add { my ($list) = @_; chomp (my $input = <STDIN>); my $newnode = [undef, $input]; $list{tail}[0]= $newnode; $list{tail}= $newnode; }
The problem is that $list is updated when you modify $$lastnode, but my ($root, $lastnode) = @_; makes $root a copy of $list and so $root is not changed. Then add() returns $root and, in effect, you end up doing $list= $root, which restores $list to its previous value.

You could change the last line of add() to be return ($_[0], $lastnode); since $_[0] is an alias to $list and not a copy of $list.

But better would be to encapsulate the $list and $lastnode variables into a single item that is passed to add() and show().

        - tye (but my friends call me "Tye")

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://142469]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-25 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found