This is from the Perl Cookbook Recipe 11.17 (Program: Binary Trees).
#!/usr/bin/perl use strict; use Data::Dumper; my $root; insert( $root, 5 ); insert( $root, 3 ); print Dumper \$root; sub insert { my ($tree, $value) = @_; unless ($tree) { $tree = {}; $tree->{VALUE} = $value; $tree->{LEFT} = undef; $tree->{RIGHT} = undef; $_[0] = $tree; # $_[0] is reference param! return; } if ( $tree->{VALUE} > $value ) { insert( $tree->{LEFT}, $value ) } elsif ( $tree->{VALUE} < $value ) { insert( $tree->{RIGHT}, $value + ) }; }
I am trying to understand the relevance of this line:
$_[0] = $tree;
He mentioned that this is a reference param. And also he mentioned that "The assignment of the new node back to $_[0] alters the value in its caller."

But I still don't get it. If I removed this line, I don't get any output.

I ran the debugger but to no avail, I still could not figure out what is the relevance of that line. Why did he write it? And is there another way to write it maybe a longer version?

Can someone help understand this? Thanks.

In reply to Binary Search Tree Debug Question by bichonfrise74

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.