简体   繁体   English

Perl grep总是返回列表上下文中的匹配数

[英]Perl grep always returns number of matches even in list context

I have a script with the lists 我有一个列表的脚本

@names = ();
@x = ();

Both lists are filled in parallel with data, therefore, in the end I have two lists with name and x-value for each element at the same index. 两个列表都与数据并行填充,因此,最后我有两个列表,其中包含同一索引中每个元素的名称和x值。 Note, there are more than one element having the same x-value. 注意,有多个元素具有相同的x值。

I want to have all elements having a specific x-value with the code 我希望所有元素都具有特定的x值和代码

foreach my $x (0..4) {      
    my @ind = grep { $x[$_] == $x } 0..$#names;
    print @ind . "\n";
}

However, the output is 但是,输出是

17
17
8
4

which is exactly the number of elements having x=0, x=1, ... 这正是x = 0,x = 1,......的元素数量

I'm wondering since grep in a list context should return me a list with the matches (here, the indizes of matching elements). 我想知道因为列表上下文中的grep应该返回一个匹配列表(这里是匹配元素的indizes)。

What am I doing wrong here? 我在这做错了什么?

Best regards. 最好的祝福。

Your problem is this line: 你的问题是这一行:

print @ind . "\n";

When you use the concatenation operator . 使用连接运算符时. you put both parameters into scalar context, and in scalar context, an array returns its size, not its content. 将两个参数放入标量上下文中,在标量上下文中,数组返回其大小,而不是其内容。

What you want is to use the comma operator instead: 你想要的是使用逗号运算符:

print @ind , "\n";

Or better yet, use the feature say : 或者更好的是,使用该功能say

say @ind;

In case what you actually want is to print the numbers in a line, separated by space: 如果你真正想要的是在一行中打印数字,用空格分隔:

say "@ind";

Or in case you want to print them separated by newlines: 或者如果您想要以换行符分隔打印它们:

say for @ind;

In all the above, say can of course be replaced by print with a newline at the end. 在上述所有的, say当然可以通过更换print ,并在最后一个新行。

You should use an array of hashes to store the data as one unit. 您应该使用哈希数组将数据存储为一个单元。 Do this where you populate @x and @names . 在那里你填充做到这一点@x@names (Assuming the x-value is in $x and the name is in $name .) (假设x值在$x ,名称在$name 。)

push @data, {
    name => $name,
    x    => $x,
};

To retrieve a name at index $i : $data[$i]{name} 要在索引$i处检索名称: $data[$i]{name}

To retrieve a x-value at index $i : $data[$i]{x} 要在索引$i处检索x值: $data[$i]{x}

To iterate over the array: 迭代数组:

for my $item_ref ( @data ){
    my $name = $item_ref->{name};
    my $x    = $item_ref->{x};
    # do something
}

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

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