如何从perl子例程中获取输出数据传递引用

时间:2011-03-21 09:43:34

标签: perl hash

如何从perl子程序获取数据..?将哈希引用传递给子例程“get_data”...填充子例程内的数据..它应该反映在外部。

前:

my %myhash = ();
get_data(\%myhash);

2 个答案:

答案 0 :(得分:1)

您通过引用传递哈希,哈希中的任何更改也将在子例程外部可见。

您是否在使用此代码时遇到任何问题?

答案 1 :(得分:1)

use strict;
use warnings;
use Data::Dumper;


my %myhash = ();
get_data(\%myhash); #pass hash ref
$myhash{k2} = "Hello SO"; #add one more key value
print Dumper($hash_ref); #Dump hash ref

sub get_data{
my $hash_ref = shift; #get hash ref
$hash_ref->{k1} = "adding one more key value"; #fill data
}

输出:

$VAR1 = {
      'k2' => 'Hello SO',
      'k1' => 'adding one more key calue'
    };