简体   繁体   English

如何从perl中的数组中过滤掉空哈希?

[英]How do I filter out empty hashes from an array in perl?

I have an array of hashes like so: 我有一系列的哈希像这样:

my @array = [
             {1 => "Test1"},
             {},
             {1 => "Test2"},
            ];

I try to filter out the {} from this array so that the end result is an array without any {} like so: 我尝试从这个数组中过滤出{},以便最终结果是一个没有任何{}的数组,如下所示:

my @array = [
             {1 => "Test1"},
             {1 => "Test2"},
            ];

I tried using something like this but it doesn't work: 我尝试使用这样的东西,但它不起作用:

my @new_array = grep(!/{}/, @array);

The grep command can take a regex as argument, but also an arbitrary block of code. grep命令可以将正则表达式作为参数,但也可以是任意代码块。 And please do not try to match Perl code with regexes, this doesn't work. 并且请不要尝试将Perl代码与正则表达式匹配,这不起作用。

Instead, we ask for the number of keys in the anonymous hash: 相反,我们要求匿名哈希中的键数:

my @new_array = grep { keys %$_ } @array;

This selects all hashes in @array where the number of keys is not zero. 这将选择@array中的所有哈希值,其中键的数量不为零。

1) A small correction: 1)一个小的修正:

my @array = [
    {1 => "Test1"},
    {},
    {1 => "Test2"},
];

Is really a 1-element array with array ref inside. 实际上是一个带有数组引用的1元素数组。 You probably need 你可能需要

my @array = (
    {1 => "Test1"},
    {},
    {1 => "Test2"},
);

2) The grep expr: 2)grep expr:

my @new_array = grep { scalar %$_ } @array;

Hash returns 0 in scalar context if it's empty, and something like "17/32" otherwise. 如果标量为空,则哈希在标量上下文中返回0,否则返回“17/32”。 So the grep will only pick non-empty arrays. 所以grep只会选择非空数组。

UPDATE: As @raina77ow suggests, scalar may be omitted! 更新:正如@ raina77ow建议的那样,标量可能会被省略! So it's even shorter (though I still prefer explicit scalar for clarity in my code). 所以它甚至更短(尽管我仍然更喜欢显式scalar以便我的代码更清晰)。

my @new_array = grep { %$_ } @array;

You need something like this: 你需要这样的东西:

my @new_array = grep(keys %$_, @array);

The /.../ in your code is a regular expression. 代码中的/.../是一个正则表达式。 It checks if each element in the array contains certain characters. 它检查数组中的每个元素是否包含某些字符。 However, your array contains references to hashes, so you need to dereference each element and then see if that is empty. 但是,您的数组包含对哈希的引用,因此您需要取消引用每个元素,然后查看它是否为空。

Also, this declaration is incorrect: 此外,此声明不正确:

my @array = [
             {1 => "Test1"},
             {},
             {1 => "Test2"},
            ];

The brackets create an array reference, while you just want an array. 括号创建一个数组引用,而您只需要一个数组。 Just use parentheses instead: 只需使用括号:

my @array = (
             {1 => "Test1"},
             {},
             {1 => "Test2"},
            );

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

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