我想得到我在函数中发送的数组,但它似乎是空的。我使用参数中的数组调用send_file();
send_file($addr, @curfile);
这是我获取参数的方法
sub send_file($$)
{
my $addr = $_[0];
my @elem = @_;
...
}
为什么my @elem
为空?我怎样才能在不损失一切的情况下夺回阵列?
不要使用原型。它们的目的是更改您不需要的源解析。
sub send_file
{
my $addr = shift;
my @elem = @_;
...
}
send_file($addr, @curfile);
您应该通过引用传递数组:
#!/usr/bin/perl
use strict;
use warnings;
my $test_scalar = 10;
my @test_array = qw(this is a test);
sub test($@)
{
my ($scalar, $array) = @_;
print "SCALAR = $scalarn";
print "ARRAY = @$arrayn";
}
test($test_scalar, @test_array);
system 'pause';
输出:
SCALAR = 10
ARRAY = this is a test
Press any key to continue . . .
编辑:
如果您想在不传递引用的情况下做同样的事情,请将$$更改为$@并使用shift,这样第一个参数就不会包含在数组中。通过引用传递数组是更好的编码实践。这只是向你展示如何在不经过参考的情况下完成:
#!/usr/bin/perl
use strict;
use warnings;
my $test_scalar = 10;
my @test_array = qw(this is a test);
sub test($@)
{
my ($scalar, @array) = @_;
print "SCALAR = $scalarn";
print "ARRAY = @arrayn";
}
test($test_scalar, @test_array);
system 'pause';
这将获得相同的输出。
如果你真的不需要,你也可以完全去掉$@。
为什么我的@elem是空的?
您的@elem
不是空的,它正好有两个元素。第一是$addr
的值,第二是@curfile
阵列中元素的大小/数量。这是由于$$
prototype
定义需要两个标量,所以scalar @curfile
作为第二个参数传递。
我怎样才能在不丢失所有东西的情况下取回阵列?
既然你没有使用原型的优势,只需省略原型部分,
sub send_file {
my ($addr, @elem) = @_;
...
}