The Perl readdir function is detailed
December 30, 2013 Perl based on a total of 763 characters Small Medium Large No comments read 4,384 times
The Readdir function reads the directory record, which is the file name, from a directory handle opened with Opendir. Use the following:
-
Readdir Dirhandle
In a scalar environment, the READDIR function returns the next directory record, otherwise it returns UNDEF. In a list environment, it returns all the remaining records in the directory, and if there are no records left, the return may be an empty list. Like what:
- Opendir(thisdir, "." ) ) or die "serious dainbramage: $!" ;
- @allfiles = Readdir Thisdir;
- Closedir Thisdir;
- Print "@allfiles\ n" ;
The above code prints all the files in the current directory on a single line. If you want to avoid "." and ".." Record, use one of the following:
- @allfiles = grep { $_ ne '. and $_ ne ' ... ' } readdir thisdir;
-
@allfiles = grep{ not/^[.][.]?\z/}Readdir Thisdir
- @allfiles = Grep { Not /^\.{ 1 , 2 } \z/ } readdir Thisdir
- @allfiles = grep ! /^\.\. ? \z/, Readdir, Thisdir;
To avoid all. * Files:
-
@allfiles = grep ! /^\./, Readdir thisdir;
Just take out the text file:
-
@textfiles = grep-t, Readdir thisdir;
But let's look at the last example, because if the result of Readdir is not in the current directory, then we need to stick the directory part back on its results-like this:
- Opendir(thatdir, $path) or die "can ' t opendir $path: $!" ;
-
@dotfile = grep{/^\./&&-F}Map{"$path/$_"}Readdir(Thatdir);
- Closedir TH
Perl readdir function to get the file in the directory