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"

我想要一个循环,它遍历所有数组元素,如果元素确实有狗,则找出其中是否有任何元素具有值“狗”,然后删除该元素。所以结果是:

@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

3 回答 3

14

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

@array = grep !/dog/, @array;
于 2013-06-20T15:14:42.913 回答
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
于 2013-06-20T15:41:09.070 回答
7
@array = grep(!/dog/, @array);
于 2013-06-20T15:36:23.317 回答