【问题标题】:Get names of all the directories with similar naming pattern in Perl获取 Perl 中所有具有相似命名模式的目录的名称
【发布时间】:2013-04-06 07:06:36
【问题描述】:

我有一个目录“logs”,其中包含子目录“A1”、“A2”、“A3”、“B1”、“B2”、“B3”。

我想编写一个 perl 代码来搜索名称模式为“A”的所有子目录,即所有以字符 A 开头的目录名称。

请帮帮我。

【问题讨论】:

  • 需要递归吗?
  • @Barmar 听起来像是在谈论子目录。
  • @squiguy 我知道,但是他需要找到子目录的子目录,子目录的子目录吗?
  • @Barmer 我只是想找到子目录。 A1、A2、B1、B2 等中没有进一步的子目录。确实,A1、A2、A3、B1、B2 等里面有很多文件。

标签: perl unix


【解决方案1】:

使用 Perl 核心模块File::Find:

use strict;
use warnings;
use File::Find;

#Find in 'logs' directory, assume the script is executed at this folder level

find(\&wanted, 'logs');

sub wanted { 
    #Subroutine called for every file / folder founded ($_ has the name of the current)
    if(-d and /^A/ ) {
       print $_, "\n"; 
    }
}

更新: 如果你想参数化前缀,你可以这样做:

use strict;
use warnings;
use File::Find;

my $prefix = 'B';

find(\&wanted, 'logs');
sub wanted { 
    if(-d and /^$prefix/ ) {
       print $_, "\n"; 
    }
}

【讨论】:

  • 嗨。这实际上是有效的。但我看到它变成了静态的。我们怎样才能使 A 成为动态的。意味着我想使用变量值代替 A。我们可以使用类似 if(-d 和 /^$val/ ) {
【解决方案2】:

File::Find 对于简单地搜索目录来说太过分了。 opendir/readdir还是有目的的!

此程序对指定目录执行chdir,因此无需根据readdir 生成的名称构建完整路径。

要搜索的目录和所需的前缀可以作为命令行参数传递,如果未提供,则默认为logsA

use strict;  
use warnings;
use autodie;

my ($dir, $prefix) = @ARGV ? @ARGV : qw/ logs A /;
chdir $dir;

my @wanted = do {
  opendir(my $dh, '.');
  grep { -d and /^\Q$prefix/ } readdir $dh;
};

print "$_\n" for @wanted;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多