如何在perl函数中发送和接收字符串、数组和散列
How send and received string, array and hash in perl function
我有过这样的情况。
my %ha = ()
my @ar = ('1','2')
my $st = 't'
f(%ha,@ar,$st);
sub f
{
my (%h, @a,$s) = @_;
或
my %h = shift;
my @a shift;
my $s = shift;
}
两者都不行。我能做什么?
您不能将复杂的数据结构作为参数传递 - 它们会被解压缩到值列表中,并且您的子例程无法分辨边界在哪里。
您可以改为传递引用:
my %hash = ()
my @arr = ('123','456')
my $str = 'test'
sub func
{
my ( $hashref, $arrayref, $str ) = @_;
my %copy_of_hash = %$hashref;
my @copy_of_array = @$arrayref;
## or you can do it by following the reference to modify the hash without copying it:
$hashref->{'key'} = "value";
}
func ( \%hash, \@arr, $str );
来自https://perldoc.perl.org/perlreftut
[ ITEMS ] 创建一个新的匿名数组,returns 引用该数组。 { ITEMS } 创建一个新的匿名散列,returns 对该散列的引用。
$aref = [ 1, "foo", undef, 13 ];
# $aref now holds a reference to an array
$href = { APR => 4, AUG => 8 };
# $href now holds a reference to a hash
因此您可以一步完成创建和引用。我发现这比反斜杠方式更简单明了。
我有过这样的情况。
my %ha = ()
my @ar = ('1','2')
my $st = 't'
f(%ha,@ar,$st);
sub f
{
my (%h, @a,$s) = @_;
或
my %h = shift;
my @a shift;
my $s = shift;
}
两者都不行。我能做什么?
您不能将复杂的数据结构作为参数传递 - 它们会被解压缩到值列表中,并且您的子例程无法分辨边界在哪里。
您可以改为传递引用:
my %hash = ()
my @arr = ('123','456')
my $str = 'test'
sub func
{
my ( $hashref, $arrayref, $str ) = @_;
my %copy_of_hash = %$hashref;
my @copy_of_array = @$arrayref;
## or you can do it by following the reference to modify the hash without copying it:
$hashref->{'key'} = "value";
}
func ( \%hash, \@arr, $str );
来自https://perldoc.perl.org/perlreftut
[ ITEMS ] 创建一个新的匿名数组,returns 引用该数组。 { ITEMS } 创建一个新的匿名散列,returns 对该散列的引用。
$aref = [ 1, "foo", undef, 13 ];
# $aref now holds a reference to an array
$href = { APR => 4, AUG => 8 };
# $href now holds a reference to a hash
因此您可以一步完成创建和引用。我发现这比反斜杠方式更简单明了。