[英]Assigning multiple values in perl, trouble with undef
I want to return several values from a perl subroutine and assign them in bulk. 我想从perl子例程返回几个值并批量分配它们。
This works some of the time, but not when one of the values is undef
: 这在某些时间有效,但在其中一个值是
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. Perl似乎将这些值连接在一起,而忽略undef元素。 Destructuring assignment like in Python or OCaml is what I'm expecting.
我期望像在Python或OCaml中那样分解结构。
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.
正如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]);
Not sure what you mean by concatenation here: 不确定在这里串联表示什么:
use Data::Dumper;
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();
print Dumper([$val, $otherval, \@arr]);
prints 版画
$VAR1 = [
'hmm',
'zap',
[
'a1',
'a2'
]
];
while: 而:
use Data::Dumper;
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();
print Dumper([$val, $otherval, \@arr]);
prints: 打印:
$VAR1 = [
'hmm',
undef,
[
'a1',
'a2'
]
];
The single difference being that $otherval is now undef instead of 'zap'. 唯一的区别是$ otherval现在是undef而不是'zap'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.