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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|