perl - 浏览目录的最佳方式是什么?

标签 perl chdir cwd

下面的两个例子都可以吗,还是第二个例子风格不好?

情况1:留在顶级目录并使用catdir访问子目录

#!/usr/bin/env perl
use warnings; use strict;

my $dir = 'my_dir_with_subdir';
my ( $count, $dh );

use File::Spec::Functions;
$count = 0;

opendir $dh, $dir or die $!;
while ( defined( my $file = readdir $dh ) ) {
    next if $file =~ /^\.{1,2}$/;
    my $sub_dir = catdir $dir, $file;
    if ( -d $sub_dir ) {
        opendir my $dh, $sub_dir or die $!;
        while ( defined( my $file = readdir $dh ) ) {
            next if $file =~ /^\.{1,2}$/;
            $count++;
        }
        closedir $dh or die $!;
    }
    else {
        $count++;
    }
}

closedir $dh or die $!;
print "$count\n";

情况2:退出前切换到子目录并恢复顶级目录

use Cwd;
my $old = cwd;
$count = 0;
opendir $dh, $dir or die $!;
chdir $dir or die $!;
while ( defined( my $file = readdir $dh ) ) {
    next if $file =~ /^\.{1,2}$/;
    if ( -d $file ) {
        opendir my $dh, $file or die $!;
        chdir $file or die $!;
        while ( defined( my $file = readdir $dh ) ) {
            next if $file =~ /^\.{1,2}$/;
            $count++;
        }
        closedir $dh or die $!;
        chdir $dir;
    }
    else {
        $count++;
    }
}
closedir $dh or die $!;
chdir $old or die $!;
print "$count\n";

最佳答案

您的问题是您是否应该更改到您正在浏览的目录或保留在顶级目录中。

答案是:这要看情况。

例如,考虑 File::Find 。默认行为确实是更改目录。然而,该模块还提供了no_chdir如果不需要,请选择。

就您的示例而言,File::Find 可能不合适,因为您不想递归遍历所有子目录,而只想递归一个子目录。这是File::Slurp::read_dir基于您的脚本的变化。

#!/usr/bin/perl

use strict; use warnings;

use File::Slurp;
use File::Spec::Functions qw( catfile );

my ($dir) = @ARGV;

my $contents = read_dir $dir;
my $count = 0;

for my $entry ( @$contents ) {
    my $path = catfile $dir, $entry;
    -f $path and ++ $count and next;
    -d _ and $count += () = read_dir $path;
}

print "$count\n";

关于perl - 浏览目录的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2243145/

相关文章:

c - 当我在 C 中更改目录时出现段错误

python - python 中的当前目录路径在类中更改

ruby - 访问与脚本相同目录中的文件

perl - 在5.6.x之后不赞成使用Perl的-w开关来警告吗?

regex - Perl 文件正则表达式不替换文本

perl - 如何将散列的一部分传递给子例程?

在 C 中更改子进程中的当前工作目录

prompt - 将提示中的部分 cwd 替换为 TCSH 中的文本

javascript - 在具有相同类的情况下,单击事件仅触发一次