2014-09-29 75 views
0

我想在perl中使用函数创建哈希。其实我正在研究在perl中创建一个二叉搜索树。下面是代码:使用函数创建哈希

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"; 
} 

麻烦的是,当我打印的原始哈希值,数据键得到由不管我是谁传递给newhash功能所取代。输出:

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

任何想法为什么数据密钥被替换?

+3

务必使用'use strict;使用警告;'! – ikegami 2014-09-29 05:18:04

回答

6

use strict;会告诉你一堆未申报的变量;用my将它们词汇化,它应该可以解决你的问题。现在,只有一个%node,并且您在每次致电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"; 
+0

如何将** foreach **循环的2行代码块合并为一行? 'foreach(keys%$ head){ 如果$ head - > {$ _};打印“head - > $ _ = $ head - > {$ _} \ n”; 打印“head - > $ _ = NULL \ n”if! $头 - > {$ _}; }' – 2014-09-30 08:15:22

0

这里是在BT结构中添加元素的代码。

使用严格;

use List :: Util qw(first);

my(@ input,$ data);

print“输入BST结构中的数据:”;

$ data = <>;;

chomp($ data);

my $ root = $ data;

push(@ input,$ data);

而($数据=〜米/ \ 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 != 

标量(@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”;