如何返回数组和hashref



我想创建一个子程序,将元素(带值的键)添加到以前定义的哈希中。此子例程是在循环中调用的,因此哈希会增长。我不希望返回的哈希覆盖现有元素。

最后,我想输出整个累积的哈希。

现在它没有打印任何内容。最后一个散列看起来是空的,但不应该是空的。我尝试过使用哈希引用,但它并没有真正起作用。简而言之,我的代码如下所示:

sub main{
  my %hash;
  %hash=("hello"=>1); # entry for testing
  my $counter=0;
  while($counter>5){ 
    my(@var, $hash)=analyse($one, $two, %hash);
    print ref($hash);
    # try to dereference the returning hash reference,
    # but the error msg says: its not an reference ...
    # in my file this is line 82
    %hash=%{$hash};
    $counter++;
  }
  # here trying to print the final hash
  print "hash:", map { "$_ => $hash{$_}n" } keys %hash;
}
sub analyse{
  my $one=shift;
  my $two=shift;
  my %hash=%{shift @_};
  my @array; # gets filled some where here and will be returned later 
  # adding elements to %hash here as in 
  $hash{"j"} = 2;  #used for testing if it works
  # test here whether the key already exists or
  # otherwise add it to the hash
  return (@array, %hash);
}

但这根本不起作用:子程序analyse接收散列,但它返回的散列引用是空的,或者我不知道。最后什么也没印出来。

首先它说,这不是一个参考,现在它说:

不能使用未定义的值作为HASH引用位于C:\Users/workspace/Perl_projekt/Extractor.pm第82行。

我的错误在哪里?

我感谢你的建议。

数组在perl中被展平,因此您的hashref被模糊到@var中。

试试这样的东西:

my ($array_ref, $hash_ref) = analyze(...)
sub analyze {
  ...
  return (@array, @hash);
}

如果通过引用传递散列(正如您所做的那样),则不必将其作为子例程返回值返回。您在子例程中对散列的操作将保持不变。

 my %h = ( test0 => 0 );
 foreach my $i ( 1..5 ) {
    do_something($i, %h);
 }
 print "$k = $vn" while ( my ($k,$v) = each %h );

 sub do_something {
   my $num = shift;
   my $hash = shift;
   $hash->{"test${num}"} = $num;  # note the use of the -> deference operator
 }

在子程序中使用@数组需要一个单独的问题:-)

最新更新