Since we've been doing linked lists in computer science
class recently but are unfortunately using the ol' Pascal
(which I've grown to dislike) I decided to code the same
simple program we finished in class - this time in Perl to see how it works.
After reading a little on that topic I made an implementation
like this :
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";
}
}
Interestingly I found out that this wasn't working.
Debugging it with Komodo 1.1 I found that after
$$lastnode = $newnode;
$list wasn't being set, which kinda defeated it's purpose.
Then I changed the implementation to this :
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";
}
}
I removed the variable passing and accessed $list and $lastnode directly.
And well, now it worked. But I don't get why passing the variable
makes example 1 don't work.
I am thankful for enlightenment.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.