perl简单匹配但不匹配

时间:2014-01-30 19:17:54

标签: perl

在blah.txt中:

/a/b/c-test

in blah.pl

  1 my @dirs;
  2 $ws = '/a/b/c-test/blah/blah';       <--- trying to match this
  3 sub blah{
  4     my $err;
  5     open(my $fh, "<", "blah.txt") or $err = "catn do it\n";
  6     if ($err) {
  7         print $err;
  8         return;
  9     } else {
 10         while(<$fh>){
 11             chomp;
 12             push @dirs, $_;
 13         }
 14     }
 15     close $fh;
 16     print "successful\n";
 17 }
 18
 19
 20 blah();
 21
 22 foreach (@dirs) {
 23     print "$_\n"; #/a/b/c-test
 24     if ($_ =~ /$ws/ ) {                  <--- didnt match it
 25         print "GOT IT!\n";
 26     } else {
 27         print "didnt get it\n";
 28     }
 29 }
~

perl blah.pl

successful
/a/b/c-test
didnt get it

我不太确定为什么它不匹配。 有人知道吗?

1 个答案:

答案 0 :(得分:3)

考虑,

if ($ws =~ /$_/ ) {  

代替,

if ($_ =~ /$ws/ ) {  

因为/a/b/c-test/blah/blah包含/a/b/c-test字符串,否则不会。

附注:

  • 至少使用strict and warnings
  • while()循环中读取并处理文件,而不是先填充数组
  • 如果您必须填充数组,请使用my @dirs = <$fh>; chomp(@dirs);
相关问题