开发者

Grep in perl never seems to work for me

I have a simple script that reads and list file from a directory. But I don't want to list hidden files, files with a " . " in front.

So I've tried using the grep function to do this, but it returns nothing. I get no listing of files.

opendir(Dir, $mydir);
while ($file = readdir(Dir)){
$file = grep  !/^\./  ,readdir Dir;
 print "$file\n";
开发者_StackOverflow中文版

I don't think I'm using the regular expression correctly. I don't want to use an array cause the array doesn't format the list correctly.


You can either iterate over directory entries using a loop, or read all the entries in the directory at once:

while (my $file = readdir(Dir)) {
    print "$file\n" if $file !~ /^\./;
}

or

my @files = grep { !/^\./  } readdir Dir;

See perldoc -f readdir.


You're calling readdir() twice in a loop. Don't.


or like so:

#!/usr/bin/env perl -w
use strict;

opendir my $dh, '.';
print map {$_."\n"} grep {!/^\./} readdir($dh);


Use glob:

my @files = glob( "$mydir/*" );
print "@files\n";

See perldoc -f glob for details.


while ($file = readdir(Dir))
{
    print "\n$file" if ( grep !/^\./, $file );
}

OR you can use a regualr expression :

while ($file = readdir(Dir))
{
    print "\n$file" unless ( $file =~ /^\./ );
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜