如果数组元素包含某个字符串,如何从数组中删除这些元素

3
假设我有一个包含以下数据的数组:
@array[0] = "hello this is a text"
@array[1] = "this is a cat" 
@array[2] = "this is a dog"
@array[3] = "this is a person"
@array[4] = "this is a computer"
@array[5] = "this is a code"
@array[6] = "this is an array"
@array[7] = "this is an element"
@array[8] = "this is a number"

我希望有一个循环,遍历所有数组元素并查找其中是否有值为"dog"的元素。如果存在"dog",则删除该元素。最终结果如下:

@array[0] = "hello this is a text"
@array[1] = "this is a cat" 
@array[2] = "this is a person"
@array[3] = "this is a computer"
@array[4] = "this is a code"
@array[5] = "this is an array"
@array[6] = "this is an element"
@array[7] = "this is a number"

4
@var[index] = ... 的风格不佳。请使用 $var[index] = ...。这个表达式使用了 $ 符号,但仍然引用了命名数组 @var。请参见 perldata - mob
3个回答

14

@array = grep not /dog/, @array;

@array = grep !/dog/, @array;

v5.16.3 给我一个错误提示 "grep 的参数不足","not" 应该是一个 "!" 吗?(另一个答案是使用 !) - David Poole
抱歉,David,“not”与“!”的优先级不同。 - mob

9

显然,重新分配整个数组更容易,但要实际循环删除,可以这样做:

use strict;
use warnings;

my @array = (
    'hello this is a text',
    'this is a cat',
    'this is a dog',
    'this is a person',
    'this is a computer',
    'this is a code',
    'this is an array',
    'this is an element',
    'this is a number'
);

for my $index (reverse 0..$#array) {
    if ( $array[$index] =~ /dog/ ) {
        splice(@array, $index, 1, ());
    }
}

print "$_\n" for @array;

输出:

hello this is a text
this is a cat
this is a person
this is a computer
this is a code
this is an array
this is an element
this is a number

$#array@array 的最后一个元素的索引(如果为空则为-1)。 - ysth

8
@array = grep(!/dog/, @array);

这会同时删除元素吗? - dataminer123
是的。您可以在此操作之前和之后打印元素(或元素计数)以查看差异。 - capiggue

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接