从perl中的另一个数组中删除一个数组中的元素

时间:2015-06-17 10:53:45

标签: perl

我希望将所有元素都清晰,将它们存储在数组中,然后从该数组中删除符号链接。问题是我不知道如何删除另一个数组中包含的所有元素,因为我是perl的新手。

到目前为止,贝娄是我的代码。

foreach ${dir} (@{code_vob_list}) 
{
    ${dir} =~ s/\n//;
    open(FIND_FILES, "$cleartool find ${dir} -type f -exec 'echo \$CLEARCASE_PN' |") or die "Can't stat cleartool or execute : $!\n"; #This command gets all files
    @{files_found} = <FIND_FILES>;

    open(SYMBOLIC_FIND_FILES, "$cleartool find ${dir} -type l -exec 'echo \$CLEARCASE_PN' |") or die "Can't stat cleartool or execute : $!\n"; #This command get all symbolic links
    @{symbolic_files_found} = <SYMBOLIC_FIND_FILES>;
    #Filter away all strings contained in @{symbolic_files_found} from @{files_found}
    foreach my ${file} (@{files_found}) 
    {
        #Here I will perform my actions on @{files_found} that not contains any symbolic link paths from @{symbolic_files_found}
    }
}

提前致谢

2 个答案:

答案 0 :(得分:5)

要过滤数组,您可以使用grep

my @nonlinks = grep { my $f = $_;
                      ! grep $_ eq $f, @symbolic_files_found }
               @files_found;

但使用哈希通常更清晰。

my %files;
@files{ @files_found } = ();            # All files are the keys.
delete @files{ @symbolic_files_found }; # Remove the links.
my @nonlinks = keys %files;

答案 1 :(得分:2)

我建议您安装并使用List::Compare。代码看起来像这样

正如我在评论中写的那样,我不确定你是否愿意写这样的标识符,而且我也不清楚你是否避免使用反引号`...`(与qx{...}相同支持管道打开是有原因的,但这更接近我编写代码的方式

如果您愿意,get_unique有同义词get_Lonly,您可能会发现更具表现力的

use List::Compare;

for my $dir ( @code_vob_list ) {

    chomp $dir;

    my @files_found = qx{$cleartool find $dir -type f -exec 'echo \$CLEARCASE_PN'};
    chomp @files_found;

    my @symbolic_files_found = qx{$cleartool find $dir -type l -exec 'echo \$CLEARCASE_PN'};
    chomp @symbolic_files_found;

    my $lc = List::Compare->new('--unsorted', \@files_found, \@symbolic_files_found);
    my @unique = $lc->get_unique;
}