如果元素包含某些字符串,则从数组中删除它

时间:2013-06-20 14:55:02

标签: arrays perl

假设我有一个包含以下数据的数组:

@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”,然后删除元素。结果将是:

@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"

3 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:8)

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

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

答案 2 :(得分:6)

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