Perl script recursively traverses the files in the directory

Time:2021-12-8
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/perl -w
use strict;
use File::Spec;
 
local $\ ="\n";#Add a newline character to each line output 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, do the following
        opendir $dh, $files[0] or die $!;#Open the directory handle and print the error message if it fails
        @_ = grep { /^[^\.]/ } readdir $dh;#Filter out files with "." and "..", that is, hidden files under UNIX
        foreach (@_) {
          push(@files, File::Spec->catfile ($files[0], $_));#Connect the directory name and file name to form a complete file path:
        }
        closedir $dh;
      }
      #If the file is pressed directly 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