Search code examples
perlforeachchomp

how to read all file names from a given directory using perl?


friends i 've this code which read file name from a directory and print those names

opendir DIR1,  "defaults" or die "cannot open dir: $!";#open the given dir
        my @default_files=readdir DIR1;
        foreach my $fls(@default_files){ 
                        chomp($fls); 
                        print "$fls\n";
           }

when i run the above code i've got

.
..
PGR.csv
report.csv
std_headers.csv
tab_name.txt

'm confused what is first two lines? thanks in advance


Solution

  • A simpler alternative can be using the glob function:

    my @default_files = glob 'defaults/*';
    

    Or:

    my @default_files = <defaults/*>;
    

    These functions filter out file and directory entries that begin with ., just like the shell does.