我如何将散列传递给Perl中的函数? [英] How do I pass a hash to a function in Perl?

查看:113
本文介绍了我如何将散列传递给Perl中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数需要一个变量和一个关联数组,但我似乎无法让它们传递正确。我认为这与函数声明有关,但我无法弄清楚它们在Perl中的工作方式。有没有一个很好的参考,我怎么做到我需要?

我应该补充说,它需要通过引用传递。

  sub PrintAA 
{
my $ test = shift;
my%aa = shift;
打印$ test。 \\\
;
foreach(键%aa)
{
print $ _。 :。 $ aa {$ _}。 \\\
;
$ aa {$ _} = $ aa {$ _}。 +;
}
}


解决方案

Pass而不是哈希本身。在

  PrintAA(abc,\%fooHash); 

sub PrintAA
{
my $ test = shift;
my $ aaRef = shift;

print $ test,\\\
;
foreach(键%{$ aaRef})
{
print $ _,:,$ aaRef-> {$ _},\\\
;


另请参阅perlfaq7:如何传递/返回{Function,FileHandle,Array,Hash,Method,Regex}?


I have a function that takes a variable and an associative array, but I can't seem to get them to pass right. I think this has something to do with function declarations, however I can't figure out how they work in Perl. Is there a good reference for this and how do I accomplish what I need?

I should add that it needs to be passed by reference.

sub PrintAA
{
    my $test = shift;
    my %aa   = shift;
    print $test . "\n";
    foreach (keys %aa)
    {
        print $_ . " : " . $aa{$_} . "\n";
        $aa{$_} = $aa{$_} . "+";
    }
}

解决方案

Pass the reference instead of the hash itself. As in

PrintAA("abc", \%fooHash);

sub PrintAA
{
  my $test = shift;
  my $aaRef = shift;

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

See also perlfaq7: How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?

这篇关于我如何将散列传递给Perl中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆