0
#array 

@myfiles = ("public", "A0", "B0", "KS"); 

Now, I just want A0, B0 and dont want any other elements like public and KS. So, for that I have below code:

my @MYFILES; 

foreach $names ( @myfiles )  {

  next if ( $names =~ m/public/);
  next if ( $names =~ m/KS/ ) ; 
  push (@MYFILES, "$names");

}  

Now, next if statements helps to skip the elements that I dont want in my new array "@MYFILES"

But, instead of next if statements, if I want to create a list of not required elements like public, KS and just call that in foreach loop which takes care and only gathers required elements like A0, B0 then how can it be done? I mean :

Something like creating hash %bad_dir = ( public = 1, KS = 1 ); and then calling that in foreach loop like below:

%bad_dir = ( public = 1, KS = 1 );

foreach $names ( @myfiles ) { 

 next if ( exists ( $bad_dirs{$names} )); 
 #but this code does not work ( Reason for creating hash is I will be having many such files that I don't need and I want to use next if statements. I want some shorter way. ) 

}

How can I do that.

thanks,

4

3 回答 3

7

perldoc -f grep对于过滤列表很有用:

use warnings;
use strict;

my @myfiles = ("public", "A0", "B0", "KS");
my %bads    = map { $_ => 1 } qw(public KS);
my @MYFILES = grep { not exists $bads{$_} } @myfiles;
于 2013-08-16T00:02:06.250 回答
1

你想多了:

use strict;
use warnings;
use feature qw(say);

my @files = qw(public A0 B0 KS);
my @not_required;
my @required;

for my $file ( @files )  {
    if ( $name =~ /public|KS/i ) {
        push @not_required, $name;
    }
    else {
        push @required, $name;
    }
}

这就是您所说的:您需要两个数组:一个必需的文件,一个是不需要的文件。if/else逻辑很清楚地表明了这一点。您正在将文件推送到数组@required@not_required数组中。

另请注意,名称应该意味着什么。您在谈论files,因此应该调用带有名称的数组,@files而不仅仅是@myname单数,即使您正在谈论一组东西。

和,use strict;use warnings;。这些将捕获大约 90% 的编程错误。

于 2013-08-16T01:03:16.077 回答
1

Check out grep: http://perldoc.perl.org/functions/grep.html

If you have a short list, you can do this (using your own correct regex, of course):

my @myfiles = grep { !/public|KS/ } @myfiles;
于 2013-08-15T23:30:46.507 回答