I tried implementing a binary tree in Perl without using any external library. My code follows. The problem is, it says:

"Use of uninitialized value in numeric eq (==) at Tree.pl line 42. Use of uninitialized value in numeric eq (==) at Tree.pl line 42."
in the traverse() function. I took help from algorithms in Perl book.
use strict; use warnings; sub search { my ($tree, $element) = @_; # we pass the root node and the element + to be found my $node; while($node = $$tree) { # $tree is a reference so we dereference i +t using $$. if($element == $node->{val}) { return($tree, $node); # return the subtree where the node +was found. } else { if($element < $node->{val}) { # go left $tree = \$node->{left}; # note that $tree is a referen +ce so we assign it a reference with '\' } else { $tree = \$node->{right}; } } } # we reach here iff there is no $element to be found # we politely suggest user that they may add the element at the gi +ven position. return ($tree, undef); } sub insert { my ($tree, $element) = @_; my $found; ($tree, $found) = search($tree, $element); unless($found) { $found = { left => undef, right => undef, val => $element, }; $$tree = $found; } return $found; } sub traverse { my $tree = shift; if($$tree->{left} == undef || $$tree->{right} == undef) { return; } traverse(\$tree->{left}); print $$tree->{val}; print "\n"; traverse(\$tree->{right}); } my @ele = [1, 2, 3, 4, 5]; my ($tree, $stat, $link); for my $ele (@ele) { ($stat, $link) = insert(\$tree, $ele); } traverse(\$tree);

As per my (limited) knowledge of Perl, I guess the search() and insert() function are correct, but I'm not sure.


In reply to Tree Data Structure by code-ninja

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.