gpt4 book ai didi

arrays - 如果它们包含一些字符串,则从数组中删除它们

转载 作者:行者123 更新时间:2023-12-02 05:21:50 26 4
gpt4 key购买 nike

可以说我有一个包含以下数据的数组:

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

最佳答案

显然,重新分配整个数组更容易,但是实际上要遍历并删除,您可以执行以下操作:

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

关于arrays - 如果它们包含一些字符串,则从数组中删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17216966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com