如何在perl子函数中传递hash

 

一。
如果是只有一个参数要传,且是hash,最直接想到的办法就是像传其他类型参数一样直接传,
如:  %relhash = count_word(%relhash);
但是:
1、too expensive
 
2、如果有超过一个参数要传,而把hash放到最前面,结果在子函数中会合并到第一个hash上面去,如:
%relhash = count_word ($filename, %relhash);
sub count_word
{
 my ($infile, %wordhash) = @_;
......
 return (%wordhash);
}
#以上虽然可以运行,但是复制了整个hash,代价比较大
 
%relhash = count_word (%relhash, $filename);
sub count_word
{
 my (%wordhash, $infile) = @_;
......
 return (%wordhash);
}
# 以上方法传递参数会出错,sub中$infile为空
 
3、如果同时传了两个hash或array,在子函数中也会合并到第一个中去,而第二个就会传不进来
 
 
二。 一种解决方法,举例: (要传两个或以上hash也可以这样做)
 
传递hash的Reference
 
print_hash($relfile, /%relhash);
 
sub print_hash
{
 my ($outfile, $wordhash) = @_;
 open OUT, ">$outfile" or die "cannot open file $outfile";
 my @array = sort { $wordhash->{$b}<=>$wordhash->{$a}} keys %$wordhash;

# 这里只能用$wordhash->{$b},而不能写成 $wordhash{$b}
 for (my $i = 0; $i<@array; $i++)
 {
  print OUT $array[$i]," ",$wordhash->{$array[$i]},"/n"; 
 } 
 close OUT;
}

 

如果子函数需要返回,也是一样的:

my %ophash;

*ophash = count_word(/%ophash, $filename);

sub count_word
{
 my ($wordhash, $infile) = @_;
 open IN, "<$infile" or die "cannot open file $infile";
 my $text = <IN>;
 close IN;
 my @array = split(//s/,$text);
 for (my $i=0; $i<@array; $i++)
 {
  $wordhash->{$array[$i]}++;
 }
 return ($wordhash);
}

 

同理,如果要传多个array:

processarrays(/@array1, /@array2);

$sub processarrays{
   my($a1, $a2) = @_;
   foreach(@$a1){    # dereferences $a1
      print $_;
   }
   for($i=0; $i<@$a2; $i++){
       print $a2->[$i];    #get at a particular index within array
   }
}

 

三。

如果不是有特别需要的话,呼呼,还是直接定义为全局变量,而不传递是最方便的啦。:P

 

文章来源: http://mzhangbj.spaces.live.com/blog/cns!6581afdaae0ec2e3!243.entry

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值