Perl readdir function to get the file in the directory

Source: Internet
Author: User


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:


    1. 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:


  1. Opendir(thisdir, "." ) ) or die "serious dainbramage: $!" ;
  2. @allfiles = Readdir Thisdir;
  3. Closedir Thisdir;
  4. 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:


  1. @allfiles = grep { $_ ne '.  and $_ ne ' ... ' } readdir thisdir;
  2. @allfiles = grep{ not/^[.][.]?\z/}Readdir Thisdir

  3. @allfiles = Grep {   Not  /^\.{ 1 , 2 } \z/ }  readdir Thisdir
  4. @allfiles = grep ! /^\.\. ? \z/, Readdir, Thisdir;


To avoid all. * Files:


    1. @allfiles = grep ! /^\./, Readdir thisdir;


Just take out the text file:


    1. @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:


  1. Opendir(thatdir, $path) or die "can ' t opendir $path: $!" ;
  2. @dotfile = grep{/^\./&&-F}Map{"$path/$_"}Readdir(Thatdir);

  3. Closedir TH





Perl readdir function to get the file in the directory


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.