====== perl 副程式傳遞多個 hash 實作 ======
Perl 傳遞參數給副程式是採用 array 的方式將各個參數傳遞過去, 所以當要傳的參數有多個 array 或 hash 時, 就會出現問題, 在 [[http://search.cpan.org/~rgarcia/perl-5.10.0/pod/perlsub.pod|perlsub]] 參考解決方案中, 是提出 array 的方法如下:
($aref, $bref) = func(\@c, \@d);
print "@$aref has more than @$bref\n";
sub func {
my ($cref, $dref) = @_;
if (@$cref > @$dref) {
return ($cref, $dref);
} else {
return ($dref, $cref);
}
}
但我現在大量使用 hash 方式, 所以花了一些時間, 試出來以下的範例:
#!/usr/bin/perl
use Data::Dumper;
$hash_h1->{'id'}='hash_h1';
$hash_h2->{'id'}='hash_h2';
$hash_h1->{'main'}->{'temp'}='Insert by main!';
print Dumper($hash_h1);
print Dumper($hash_h2);
($hash_h2, $hash_h1) = mysub1(\$hash_h1, \$hash_h2);
print Dumper($hash_h1);
print Dumper($hash_h2);
sub mysub1 {
local($hash1, $hash2) = @_;
$$hash1->{'main'}->{'temp'}='hash1 Update by mysub1:'.time;
$$hash2->{'main'}->{'temp'}='hash2 Update by mysub1:'.time;
return($$hash1, $$hash2);
}
** 呼叫 mysub1() 前: **
$hash_h1 = {
'id' => 'hash_h1',
'main' => {
'temp' => 'Insert by main!'
}
};
$hash_h2 = {
'id' => 'hash_h2'
};
** 呼叫 mysub1() 後: **
$hash_h1 = {
'id' => 'hash_h2',
'main' => {
'temp' => 'hash2 Update by mysub1:1229088705'
}
};
$hash_h2 = {
'id' => 'hash_h1',
'main' => {
'temp' => 'hash1 Update by mysub1:1229088705'
}
};
* ** 重點在呼叫時的 hash 參數變數要加上 \**
Exp. ($hash_h2, $hash_h1) = mysub1**(\$hash_h1, \$hash_h2)**;
* ** 在副程式內所使用的 hash 變數因為都是 ref 所以必須在變數前加上 $ 轉回**
Exp. **$$hash1->{'main'}->{'temp'}**='hash1 Update by mysub1:'.time;
* ** 副程式要回傳處理結果時, 也必須加上 $ 轉回**
Exp. return**($$hash1, $$hash2)**;
===== 參考網路資料頁面 ====
* [[http://search.cpan.org/~rgarcia/perl-5.10.0/pod/perlsub.pod|perlsub - Perl subroutines]]
{{tag>perl sub hash}}