Perl:如何在子例程中更改全局哈希中的值

时间:2013-06-13 05:55:30

标签: perl hash perl-data-structures

我有一个全局哈希

our %employee = (
    'ename'=>"rahul",
    'eno'=>"25",
);

后来我想在子程序中使用它,并使用不同的值

sub emp
{
    print ("$employee->'ename' = 'satish'");
}

但这没有发生,请你告诉我这里有什么问题。?

2 个答案:

答案 0 :(得分:4)

%employee是散列而不是散列引用。因此,请尝试修改$employee{'ename'}= "Satish";

之类的值
use strict;

our %employee = ( 
    'ename' => "rahul",
    'eno'   => "25",
);

sub emp {
    print "Original Value: $employee{'ename'} \n";
    $employee{'ename'} = "Satish";
    print "Modified Value: $employee{'ename'}\n";
}

emp();

输出:

Original Value: rahul
Modified Value: Satish

答案 1 :(得分:1)

就像修改另一个哈希值一样。

假设您有这样的包裹:

package TestPack;

use warnings;
use strict;

our %employee = (
    ename => 'rahul',
    eno   => 25,
);

您可以像这样修改hash

#!/usr/bin/perl

use warnings;
use strict;

use TestPack;

print "name: $TestPack::employee{'ename'}\n";

$TestPack::employee{'ename'} = "Chris";
print "name: $TestPack::employee{'ename'}\n";

输出:

$ ./test.pl 
name: rahul
name: Chris

虽然在处理有很多人的大型项目时直接处理数据可能不是最好的,但是你可以在TestPack中找到类似“访问者/变种者”的东西:

sub get_value {
    my $val = shift;

    if( exists($employee{$val}) ) {
        return $employee{$val};
    } else {
        return "No such value: $val";
    }
}

sub update_ename {
    my $ename = shift;

    $employee{'ename'} = $ename;
}

其他模块/脚本可以添加如下内容:

my $new_new_ename = "Mike";

TestPack::update_ename($new_new_ename);
print "name: ", TestPack::get_value('ename'), "\n";
print "name: ", TestPack::get_value('foobar'), "\n";

输出:

name: Mike
name: No such value: foobar