简体   繁体   English

删除 Perl 中的数组数组中的 undef

[英]Remove undef in an array of array in Perl

I am trying to remove the element from the array of array which has undef value.我正在尝试从具有 undef 值的数组数组中删除元素。

I want the output to be:我希望 output 是:

@list = [
      [
        2,
        ""
      ],
      [
        4,
        ""
      ],
      [
        6,
        ""
      ],
      [
        8,
        ""
      ],
      [
        10,
        ""
      ],
    ];

This is what I have been trying to remove the undef from the array.这就是我一直试图从数组中删除 undef 的内容。 I am grepping the defined element from the array, but its not working我正在从数组中提取定义的元素,但它不起作用

use Data::Dumper;

my @list = [
  [
    undef,
    ""
  ],
  [
    2,
    ""
  ],
  [
    4,
    ""
  ],
  [
    6,
    ""
  ],
  [
    8,
    ""
  ],
  [
    10,
    ""
  ],
];

@list = grep defined, @list;

print Dumper(\@list);

Can someone please help?有人可以帮忙吗?

Thanks in advance提前致谢

People often get lists and arrays confused in Perl.人们经常在 Perl 中混淆列表和 arrays。 So calling an array variable @list is a really bad idea:-)所以调用数组变量@list是一个非常糟糕的主意:-)

As I mentioned in a comment, you seem to be confused about how you populate an array in Perl.正如我在评论中提到的,您似乎对如何在 Perl 中填充数组感到困惑。 You either populate it with a list:您可以使用列表填充它:

my @array = ( ... ); # Lists use parentheses

Or you create an anonymous array and store a reference to that array in a scalar variable:或者您创建一个匿名数组并将对该数组的引用存储在标量变量中:

my $array_ref = [ ... ]; # Anon array uses square brackets

Next, your array doesn't contain undef elements.接下来,您的数组不包含undef元素。 Every element in your array is a reference to a two-element array.数组中的每个元素都是对二元素数组的引用。 In one of those second-level arrays, the first element is undef .在其中一个二级 arrays 中,第一个元素是undef You're right to use grep to filter the array, but you need to look at the second-level array to do what you want.使用grep对数组进行过滤是对的,但是您需要查看二级数组才能执行您想要的操作。

So the code would look something like this:所以代码看起来像这样:

my @array = ( ... );

@array = grep { defined $_->[0] } @array;

Note that I've switched to the block syntax of grep .请注意,我已切换到grep的块语法。 This is the most commonly-used version and it's probably best to use that syntax.这是最常用的版本,最好使用该语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM