AnuragChauhan
AnuragChauhan

Reputation: 163

Check existence of files with a given extension in a directory

I don't want to specify a file name, want to use only extension.

like

if(-e "./dir/*.c"){
}

I want to check if any .c file exist in ./dir directory. Is it possible ? Since I am not getting the correct result, If someone knows any alternative or correct way to use this -e switch in this scenario, please help me.

Upvotes: 1

Views: 3414

Answers (2)

phoxis
phoxis

Reputation: 61920

This may help:

my @list = <*.c>;

if (scalar @list == 0) {
  print "No .c File exist.";
} else {
  print "Existing C files are\n", join (", ", @list), "\n";
}

Instead of spawning a subshell by expanding the file list using glob <*.c> you can also use the opendir, readdir functions as follows:

opendir DIR, $path;
my @list = readdir DIR;
closedir (DIR);
my $flag = 0;

foreach $file (@list) {
  if ($file =~ m/^.*\.c$/i) {
    print "$file\n";
    $flag = 1;
  }
}

if ($flag == 0) {
  print "No .c file exists\n";
}

Where $path is a variable which indicates the path of the directory.

Upvotes: 5

TLP
TLP

Reputation: 67890

You might be interested in the File::Find module, which is a core module in Perl version 5. It is recursive, which may or may not be what you want.

use strict;
use warnings;
use File::Find;
use Data::Dumper;   # for output only

my @found;
find(sub { /\.c$/i && push @found, $File::Find::name; }, 'dir');
print Dumper \@found;

$File::Find::name contains the full path for the file. The regex matches against the $_ which contains the base file name. Note that the first argument to the find() subroutine is an anonymous sub, a code block.

If you want to check for empty output, using the array in scalar context returns its size. A zero (false) size means no matches were found.

if (@found) {
    print "Found files: @found\n";
} else { ...}

Upvotes: 2

Related Questions