代码之家  ›  专栏  ›  技术社区  ›  Wes

忽略列表分配中的元素的最佳方式是什么?

  •  3
  • Wes  · 技术社区  · 2 年前

    我使用列表分配将制表符分隔的值分配给不同的变量,如下所示:

    perl -E '(my $first, my $second, my $third) = split(/\t/, qq[a\tb\tc]); say $first; say $second; say $third;'
    a
    b
    c
    

    要忽略一个值,我可以将其分配给一个伪变量:

    perl -E '(my $first, my $dummy, my $third) = split(/\t/, qq[a\tb\tc]); say $first; say $third;'
    a
    c
    

    我不喜欢有未使用的变量。还有别的办法吗?

    2 回复  |  直到 2 年前
        1
  •  5
  •   toolic    2 年前

    您可以使用 undef :

    use warnings;
    use strict;
    use feature 'say';
    
    (my $first, undef, my $third) = split(/\t/, qq[a\tb\tc]);
    say $first; 
    say $third;
    

    输出

    a
    c
    
        2
  •  0
  •   brian d foy    2 年前

    您可以使用列表切片:

    my ($first, $third) = ( split(/\t/, qq[a\tb\tc]) )[0,2];
    

    与数组切片类似,例如。 @array[0,2] ,您可以从列表中抽取一部分。

        3
  •  0
  •   BarneySchmale    2 年前

    在里面 my 声明 undef 用作占位符。因此

    my ($first, undef, $third) = split(/\t/, qq[a\tb\tc]);
    

    也是可能的。