【问题标题】:Assigning multiple values in perl, trouble with undef在perl中分配多个值,undef的麻烦
【发布时间】:2011-03-17 08:17:44
【问题描述】:

我想从 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]);

【问题讨论】:

  • 一种简单的方法是返回对数组或哈希的引用并将其取消引用到您的变量中。通过返回一个标量(引用是标量),您可以最大限度地减少对上下文的担忧。
  • 在我当前的代码中,我得到的是 \undef 而不是 undef,所以我会尝试散列的东西。 Dumper 看起来很有用。
  • 你得到的是标量的引用而不是标量本身吗?
  • 是的,不知何故。现在我对 defined($otherval) 的测试失败了。
  • 您可以使用哈希切片从哈希中提取一系列值。代替 ($h{'s'}, $h{'a'}) 使用 @h{'s' , 'a'} 或 @h{qw{s a}}

标签: perl undef


【解决方案1】:

不知道这里的连接是什么意思:

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

打印

$VAR1 = [
          'hmm',
          'zap',
          [
            'a1',
            'a2'
          ]
        ];

同时:

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

打印:

$VAR1 = [
          'hmm',
          undef,
          [
            'a1',
            'a2'
          ]
        ];

唯一的区别是 $otherval 现在是 undef 而不是 'zap'。

【讨论】:

  • 看起来我在简化测试用例时修复了一些问题。我将不得不在我的 reflog 中挖掘原件。对不起。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多