目标:从阵列删除数组元素完全
我写了一个脚本,删除特定的值,并将其工作正常,但我不开心我写它的方式。所以我很想知道是否有更好的方式来编写它。请考虑下面的使用案例:
我有一个嵌套的散列/散列/数组...像下面。我需要删除其中有他们的名字local
任何数组值:
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
my $hash = { esx1 =>
{ cluster => "clu1",
fd => "fd1",
ds => [
'ds1',
'ds2',
'localds',
],
},
esx2 =>
{ cluster => "clu2",
fd => "fd2",
ds => [
'ds3',
'ds4',
'dslocal',
],
},
};
foreach my $a (keys %$hash)
{
foreach (0..$#{ $hash->{$a}->{ds} })
{
delete $hash->{$a}->{ds}->[$_] if $hash->{$a}->{ds}->[$_] =~ /local/i;
@{ $hash->{$a}->{ds} } = grep defined, @{ $hash->{$a}->{ds} };
}
}
print Dumper ($hash);
所以脚本删除了“localds
”和“dslocal
”,并保持一切完好无损。
问题:
- 是否有写
foreach (0..$#{$hash->{$a}->{ds} })
环 - 如果我不写上面的
grep
线清洁器的方式,将得到的阵列具有含local
删除的值,但由替换undef
。这是为什么发生。
谢谢。
完美。非常感谢。这种方式更加简洁,易于理解。我从一开始就知道必须有一种更简单的方法来完成这项工作。就是这个。谢谢你的时间。 – slayedbylucifer