mosh has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I need a function or module that can get the filenames that located in specific directory.

Meaning for instance, within directory "c:\directory" I have 3 files: a.txt, b.txt, c.txt, I would like a function or module that takes the specified directory and return to me a list (array) of the files that located in the specified directory.

Any ideas ?

MoshMonk.

Replies are listed 'Best First'.
Re: Files within specified directory
by fishbot_v2 (Chaplain) on Dec 11, 2005 at 18:05 UTC

    See also opendir and readdir:

    opendir( my $dirh, $dirname ) or die( "can't opendir '$dirname': $!" ); my @filenames = readdir( $dirh ); # check that readdir returned values # grep through names, etc...
Re: Files within specified directory
by tirwhan (Abbot) on Dec 11, 2005 at 17:53 UTC
    perldoc -f glob

    use File::Spec; my $path=File::Spec->catfile(qw( path to file),"*.txt"); my @files=glob($path);

    Update: included directory handling with File::Spec


    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan
Re: Files within specified directory
by NetWallah (Canon) on Dec 11, 2005 at 18:06 UTC
    You could use the built-in readdir function:
    perldoc -f readdir

    For a directory opened by opendir, readdir, if used in list context, returns all the entries in the directory.

         You're just jealous cause the voices are only talking to me.

         No trees were killed in the sending of this message.    However, a large number of electrons were terribly inconvenienced.

Re: Files within specified directory
by swampyankee (Parson) on Dec 11, 2005 at 22:06 UTC

    Or you could use File::Glob. You can either chdir() into the directory or use the directory name in the glob.

Re: Files within specified directory
by vishi83 (Pilgrim) on Dec 12, 2005 at 04:59 UTC

    Hi !!

    Sorry, If am late on this ! Hope this mite help u .

    use strict; use warnings; use File::Find::Rule; my $path = '/home/vishi83'; my $rule = File::Find::Rule->new; $rule->file; $rule->name('*.txt'); my @filez = $rule->in($path);
    untested : ( am using Unix machine ) Think You will get all the files within the sub-directories too..

    Am sure , this is pretty clear, $path holds ur pathname (c:/directory).. Also read perldoc of File::Find::Rule . It has got plenty of options , so we can do such things with ease.

    Thank u !!

    A perl Script without 'strict' is like a House without Roof; Both are not Safe;
      Thanks a lot guys !!!