开发者

How to use regex on file test operator [duplicate]

This question already has answers here: 开发者_JAVA百科 Closed 11 years ago.

Possible Duplicate:

File name matching with -e and regular expressions in perl.

for ex

if (-e /home/tree/a*) { print "file found" }

How to use regex on file test operator


You can't use a regex on the file existence test operator.

If you want to check a filename for existence using a regex, you will have to retrieve a file list, using e.g. readdir or glob (note that glob has lightweight syntax as </home/tree/*>), and then filter it using regexes.

Note that in your case, that "expression" you use, /home/tree/a*, could be interpreted as a glob pattern instead of a regex. If that's what you intended, you could use a glob directly, as in:

if ( () = </home/tree/a*> ) { print "file found" }

See comments for a discussion of why/how not to use glob as a test condition.


How come no one likes readdir()? I stopped using glob the first time I ran into the state issue mentioned in Sean's comment to JB's answer.

This will give you an idea of how to use readdir:

opendir(DIR, "/home/tree") or die $!;
my @matches = grep(/^a.*/, readdir(DIR));
closedir(DIR);
print join("\n", @matches);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜