1. ホーム
  2. スクリプト・コラム
  3. パール

ディレクトリ内のファイルを再帰的に走査するためのPerlスクリプト

2022-01-03 17:02:09
#! /usr/bin/perl -w
use strict;
use File::Spec;

local $\ ="\n";#Add line breaks to each line of output for the current module  

my %options;

# directory path
$options{single_case} = '/home/jiangyu/src/pl/Example';

  my @cases;
  if (-d $options{single_case}) {# determine if 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 directory handle, print error message if it fails
        @_ = grep { /^[^\.] / } readdir $dh;# filter out directories with ". " and ". " files, i.e. hidden files under UNIX
        foreach (@_) {
          push(@files, File::Spec->catfile ($files[0], $_));# Concatenate directory names and file names 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 list of files