在 perl 中分配多个值,undef 出现问题
我想从 perl 子例程返回几个值并批量分配它们。
这在某些时候有效,但当其中一个值为 undef
时则无效:
sub return_many {
my $val = 'hmm';
my $otherval = 'zap';
#$otherval = undef;
my @arr = ( 'a1', 'a2' );
return ( $val, $otherval, @arr );
}
my ($val, $otherval, @arr) = return_many();
Perl 似乎连接了这些值,忽略了 undef 元素。我期待像 Python 或 OCaml 中那样解构赋值。
有没有一种简单的方法可以将返回值分配给多个变量?
编辑:这是我现在用来传递结构化数据的方式。正如 MkV 建议的那样,@a 数组需要通过引用传递。
use warnings;
use strict;
use Data::Dumper;
sub ret_hash {
my @a = (1, 2);
return (
's' => 5,
'a' => \@a,
);
}
my %h = ret_hash();
my ($s, $a_ref) = @h{'s', 'a'};
my @a = @$a_ref;
print STDERR Dumper([$s, \@a]);
I want to return several values from a perl subroutine and assign them in bulk.
This works some of the time, but not when one of the values is undef
:
sub return_many {
my $val = 'hmm';
my $otherval = 'zap';
#$otherval = undef;
my @arr = ( 'a1', 'a2' );
return ( $val, $otherval, @arr );
}
my ($val, $otherval, @arr) = return_many();
Perl seems to concatenate the values, ignoring undef elements. Destructuring assignment like in Python or OCaml is what I'm expecting.
Is there a simple way to assign a return value to several variables?
Edit: here is the way I now use to pass structured data around. The @a array needs to be passed by reference, as MkV suggested.
use warnings;
use strict;
use Data::Dumper;
sub ret_hash {
my @a = (1, 2);
return (
's' => 5,
'a' => \@a,
);
}
my %h = ret_hash();
my ($s, $a_ref) = @h{'s', 'a'};
my @a = @$a_ref;
print STDERR Dumper([$s, \@a]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定这里的串联是什么意思:
prints
while:
prints:
唯一的区别是 $otherval 现在是 undef 而不是 'zap'。
Not sure what you mean by concatenation here:
prints
while:
prints:
The single difference being that $otherval is now undef instead of 'zap'.