我有一个全局哈希
our %employee = (
'ename'=>"rahul",
'eno'=>"25",
);
稍后我想在具有不同值的子程序中使用它
sub emp
{
print ("$employee->'ename' = 'satish'");
}
但这没有发生,你能告诉我这里有什么问题吗..?
我有一个全局哈希
our %employee = (
'ename'=>"rahul",
'eno'=>"25",
);
稍后我想在具有不同值的子程序中使用它
sub emp
{
print ("$employee->'ename' = 'satish'");
}
但这没有发生,你能告诉我这里有什么问题吗..?
%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
就像你会修改另一个哈希值一样。
假设你有一个这样的包:
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