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.
سؤال
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
المحلول
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.
نصائح أخرى
The first to lines are:
.
link to the directory you are currently visiting.
..
link to the directory above the directory (parent directory) you are visiting.
EDIT:
One possibility to filter out both named entries would be using grep
:
opendir DIR1, "tmp" or die "cannot open dir: $!";
my @default_files= grep { ! /^\.\.?$/ } readdir DIR1;
foreach my $fls (@default_files) {
chomp($fls);
print "$fls\n";
}
"." means the present working directory and ".." means the parent directory of the present working directory
In a directory listing, .
stands for Working Directory and ..
stands for Parent Directory.
In scalar context, you can skip those entries by explicitly checking for them:
while (defined(my $next = readdir $dir)) {
next if $next =~ /\A[.][.]?\z/;
# ...
}
or in list context:
my @entries = grep !/\A[.][.]?\z/, readdir $dir;
If I am already using File::Slurp, I prefer to just use the read_dir
function it provides. The following will automatically skip .
and ..
in addition to prepending the path to the directory to each returned entry:
my @paths = read_dir('/path/to/dir', prefix => 1);