tags:

views:

98

answers:

4
my $pat = '^x.*d$';

my $dir = '/etc/inet.d';

if ( $dir =~ /$pat/xmsg ) { 

print "found ";

}

how to make it sucess

+13  A: 

Your pattern is looking for strings starting with x (^x) and ending in d (d$). The path you are trying does not match as it doesn't start with x.

ar
+4  A: 

There is an 'x' too much :

my $pat = '^.*d$'; 
my $dir = '/etc/inet.d';
if ( $dir =~ /$pat/xmsg ) { 
  print "found ";
}
Peter Tillemans
+4  A: 

You can use YAPE::Regex::Explain to help you understand regular expressions:

use strict;
use warnings;

use YAPE::Regex::Explain;
my $re = qr/^x.*d$/xms;
print YAPE::Regex::Explain->new($re)->explain();

__END__

The regular expression:

(?msx-i:^x.*d$)

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?msx-i:                 group, but do not capture (with ^ and $
                         matching start and end of line) (with .
                         matching \n) (disregarding whitespace and
                         comments) (case-sensitive):
----------------------------------------------------------------------
  ^                        the beginning of a "line"
----------------------------------------------------------------------
  x                        'x'
----------------------------------------------------------------------
  .*                       any character (0 or more times (matching
                           the most amount possible))
----------------------------------------------------------------------
  d                        'd'
----------------------------------------------------------------------
  $                        before an optional \n, and the end of a
                           "line"
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

Also, you should not need the g modifier in this case. The documentation has plenty of information about regexes: perlre

toolic
+3  A: 

My guess is that you're trying to list all files in /etc/init.d whose name matches the regular expression.

Perl isn't smart enough to figure out that when you name a string variable $dir, assign to it the full pathname of an existing directory, and pattern match against it, you don't intend to match against the pathname, but against the filenames in that directory.

Some ways to fix this:

perldoc -f glob
perldoc -f readdir
perldoc File::Find

You may just want to use this:

if (glob('/etc/init.d/x*'))
{
  warn "found\n";
}
reinierpost