acidblue
acidblue

Reputation: 1

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";

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.

Upvotes: 0

Views: 312

Answers (5)

shawnhcorey
shawnhcorey

Reputation: 3601

Use glob:

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

See perldoc -f glob for details.

Upvotes: 1

BadFileMagic
BadFileMagic

Reputation: 701

or like so:

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

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

Upvotes: 1

Shalini
Shalini

Reputation: 455

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 =~ /^\./ );
}

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

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.

Upvotes: 4

bart
bart

Reputation: 7767

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

Upvotes: 3

Related Questions