Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在perl函数中发送和接收字符串、数组和散列_Perl - Fatal编程技术网

如何在perl函数中发送和接收字符串、数组和散列

如何在perl函数中发送和接收字符串、数组和散列,perl,Perl,我喜欢这种情况 my %ha = () my @ar = ('1','2') my $st = 't' f(%ha,@ar,$st); sub f { my (%h, @a,$s) = @_; 或 两者都不起作用。我能做什么?您不能将复杂的数据结构作为参数传递-它们会被解压到值列表中,并且您的子例程无法知道边界在哪里 您可以做的是传递引用: my %hash = () my @arr = ('123','456') my $str = 'test' sub func { my (

我喜欢这种情况

my %ha = ()
my @ar = ('1','2')
my $st = 't'

f(%ha,@ar,$st);

sub f
{

my (%h, @a,$s) = @_;


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

您不能将复杂的数据结构作为参数传递-它们会被解压到值列表中,并且您的子例程无法知道边界在哪里

您可以做的是传递引用:

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

[ITEMS]创建一个新的匿名数组,并返回对该数组的引用。{ITEMS}生成一个新的匿名哈希,并返回对该哈希的引用

$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
因此,您可以在一个步骤中创建和引用。我发现这比反斜杠更简单、更清晰。

Nit:可以传递引用。通过引用传递意味着其他东西(Perl总是通过引用传递)。请阅读以了解有关调用子例程和解析参数的更多信息。
$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