Subhayan Bhattacharya
Subhayan Bhattacharya

Reputation: 5723

Creating a hash using a function

I am trying to create a hash using a function in perl. Actually i was working on creating a binary search tree in perl. Below is the code :

sub newhash {
  $data = shift;
  $left = undef;
  $right = undef;
  %node = ("data"=>$data,"left"=>$left,"right"=>$right);
  return (\%node);
}

$firstele = newhash(2);
foreach ( keys %$firstele )
{
  print "$_:$firstele->{$_}\n";
}

$node = newhash(1);

foreach ( keys %$node )
{
  print "$_:$node->{$_} \n";
}

foreach ( keys %$firstele )
{
  print "$_:$firstele->{$_}\n";
}

The trouble is that when i am printing the original hash, the data key gets replaced by whatever i am passing to the newhash function . The output:

left:
right:
data:2
left:
right:
data:1
left:
right:
data:1

Any ideas why is the data key getting replaced?

Upvotes: 0

Views: 129

Answers (2)

karthick Sundaram
karthick Sundaram

Reputation: 33

Here is the code for adding elements in BT structure.

use strict;

use List::Util qw(first);

my (@input,$data);

print "Enter the data for being in a BST structure: ";

$data=<>;

chomp($data);

my $root=$data;

push(@input,$data);

while($data =~ m/\b-?\d{1,3}\b/){

my $idx=first { $input[$_] == $root } 0..$#input;

    if($data<$root) {

        for(my $i=0;$i<=$idx;$i++) {

            next if($data>$input[$i]) ;

            if($data<$input[$i]) {

                splice(@input,$i,0,$data);

            }

            last;

        }

    }

    if($data>$root) {

        for(my $i=$idx;$i<=$#input;$i++) {

            if($data>$input[$i]) {

                if(($i+1==scalar(@input)) or ($data<$input[$i+1] && $i+1 != 

scalar(@input))) {

                    splice(@input,$i+1,0,$data);

                    last;

                }

                else  {

                    next;

                }

            }               

            last;

        }

    }

print "Enter the number for being in a BT structure: ";

$data=<>;

chomp($data);   

}

print "Final BT Array:\n",join(',', @input),"\n";

Upvotes: 0

Jim Davis
Jim Davis

Reputation: 5290

use strict; would tell you about a bunch of undeclared variables; lexicalize them with my and it should solve your problem. As it stands, there's only one %node and you overwrite it with every call to newhash.

use strict;

sub newhash {
    my $data = shift;
    my $left;
    my $right;
    my %node = ( # <-- a brand new %node every time
        data  => $data,
        left  => $left,
        right => $right,
    );
    return (\%node); # new %node, new reference
}

my $firstele = newhash(2);
print "firstele data: $firstele->{data}\n";

my $node = newhash(1);
print "node     data: $node->{data}\n";    
print "firstele data: $firstele->{data}\n";

Upvotes: 6

Related Questions