Perl recursively iterates through the files in the directory

Source: Internet
Author: User

#! / usr / bin / perl -w
use strict;
use File :: Spec;

local $ \ = "\ n"; # Add a newline character to the output of each line of the current module

my% options;

#Directory path
$ options {single_case} = ‘/ home / jiangyu / src / pl / Example’;

   my @cases;
    if (-d $ options {single_case}) {# Determine whether the directory exists
        my @files;
        my $ dh;
        push (@files, $ options {single_case});
        while (@files) {
            if (-d $ files [0]) {#If it is a directory, perform the following operations
                opendir $ dh, $ files [0] or die $ !; #Open the directory handle and print an error message if it fails
                @_ = grep {/^[^\.]/} readdir $ dh; #filter out files with "." and "..", which are hidden files under UNIX
                foreach (@_) {
                    push (@files, File :: Spec-> catfile ($ files [0], $ _)); #Connect directory name and file name to form a complete file path:
                }
                closedir $ dh;
            }
            #If the file is directly pressed into the array @cases
            elsif ($ files [0] = ~ /\.t$/) {
                push (@cases, $ files [0]);
            }
            shift @files;
        }
    }
    else {
        @cases = ($ options {single_case});
    }


print $ _ foreach @cases; #print file list

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.