簡體   English   中英

在perl中分配多個值,undef麻煩

[英]Assigning multiple values in perl, trouble with 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]);

不確定在這里串聯表示什么:

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'。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM