Warm tip: This article is reproduced from serverfault.com, please click

其他-如何在Perl函数中发送和接收字符串,数组和哈希

(其他 - How send and received string, array and hash in perl function)

发布于 2020-11-30 13:27:51

我喜欢这种情况。

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;
}

两者都不起作用。我能做什么?

Questioner
Beso
Viewed
0
121k 2020-12-01 05:23:54

你不能将复杂的数据结构作为参数传递-它们被解包为值列表,并且子例程无法分辨边界在哪里。

你可以做的是传递引用:

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 );