我怎样才能将标量变量和数组变量传递给Perl中的子程序?
my $currVal = 1;
my $currValTwo = 1;
my @currArray = ('one','two','three');
my @currArrayTwo =('one','two','three');
&mysub($currVal, $currValTwo,\@currArray, \@currArrayTwo);
sub mysub() {
# That doesn't work for the array as I only get the first element of the array
my($inVal, $inValTwo, @inArray, @inArrayTwo) = @_;
}
Run Code Online (Sandbox Code Playgroud)
Bla*_*iev 15
您需要将它们作为引用获取,因为您已经将它们作为引用传递(通过使用\运算符):
my($inVal, $inValTwo, $inArray, $inArrayTwo) = @_;
Run Code Online (Sandbox Code Playgroud)
然后将引用用作数组:
@{$inArray}
Run Code Online (Sandbox Code Playgroud)
您将参数作为引用传递,因此您需要取消引用它们以使用这些值.是否要更改原始数组时要小心.
sub mysub {
my($inVal, $inValTwo, $inArray, $inArrayTwo) = @_;
@{$inArrayTwo} = ('five','six','seven');
}
Run Code Online (Sandbox Code Playgroud)
这将改变原件@currArrayTwo,这可能不是你想要的.
sub mysub {
my($inVal, $inValTwo, $inArray, $inArrayTwo) = @_;
my @ATwo = @{$inArrayTwo};
@ATwo = ('five','six','seven');
}
Run Code Online (Sandbox Code Playgroud)
这只会复制值并使原始数组保持原样.
此外,您不需要在perldoc perlsub的子名称前面使用&符号:
如果使用&form调用子例程,则参数列表是可选的,如果省略,则不为子例程设置@_数组:调用时的@_数组对子例程可见.这是新用户可能希望避免的效率机制.
在您的子声明后,您不需要空的parens.这些用于设置原型,这是你不需要做的事情,除非你真的想要.
| 归档时间: |
|
| 查看次数: |
11912 次 |
| 最近记录: |