Blurman
Blurman

Reputation: 609

Pattern matching perl

I am trying to search any file matching this condition *_abc_*.txt in a folder. I knew my regex usage is wrong but somehow I do not know how to fix. Thanks in advance.

chdir $dir;
opendir my $dh, $dir or die "can't open directory:$!";
while (my $entry = readdir $dh){

  if($entry !~ m{\ *?_abc_*?[.]txt\z}x){

  <do_something>

  }
}

Upvotes: 2

Views: 91

Answers (2)

opendir my $dh, $dir or die "can't open directory:$!";
while (my $entry = readdir $dh){
  if($entry !~ m{(.*?)\_abc\_(.*?)\.txt$}i){
    print $entry,"\n";
  }
}

Try the above. It will workout.

Upvotes: 3

Sobrique
Sobrique

Reputation: 53478

* doesn't mean the same thing in regex as it does in shell globs. They're similar, but not the same.

* means zero or more occurrences of the preceding match. So \ * matches zero or more spaces. _* matches zero or more underscores. So a * in glob, would be functionally equivalent to .* in a regex.

Whilst I can point you how to fix your regex, I think a better answer would be to use glob in the first place:

foreach my $filepath ( glob ( "$dir/*_abc_*.txt" ) ) {
  # do something
} 

And not try and regex match in the first place.

Upvotes: 4

Related Questions