Arrays 从数组中删除包含字符串的元素
假设我有一个包含以下数据的数组:Arrays 从数组中删除包含字符串的元素,arrays,perl,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
@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"
@array=grep not/dog/,@array代码>
显然,重新分配整个阵列更容易,但要实际循环并删除,您可以执行以下操作:
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
@var[index]=…
的风格不好。使用$var[index]=…
。此表达式使用$
符号,但仍引用命名数组@var
。请参阅。这是否也删除了元素?是。您可以在此操作之前和之后打印元素(或元素计数)以查看差异。$#array
是@array
的最后一个元素的索引(如果为空,则为-1)。v5.16.3给了我一个错误“grep的参数不够”;“not”应该是“!”?(另一个答案是使用!)对不起,David,not
的优先级与不同代码>
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