使用通配符检查Perl中是否存在目录

时间:2012-07-25 15:53:58

标签: perl

我需要检查Perl脚本中是否存在任何一组目录。目录以XXXX * YYY格式命名 - 我需要检查每个XXXX并输入if语句,如果为true。

在我的脚本中,我有两个变量$ monitor_location(包含要扫描的根目录的路径)和$ clientid(包含XXXX)。

下面的代码段已经展开,以展示我正在做的更多内容。我有一个返回每个客户端ID的查询,我然后循环返回每个返回的记录并尝试计算该客户端ID使用的磁盘空间。

到目前为止,我有以下代码(不起作用):

# loop for each client
while ( ($clientid, $email, $name, $max_record) = $query_handle1->fetchrow_array() )
{
  # add leading zeroes to client ID if needed
  $clientid=sprintf"%04s",$clientid;

  # scan file system to check how much recording space has been used
  if (-d "$monitor_location/$clientid\*") {
    # there are some call recordings for this client
    $str = `du -c $monitor_location/$clientid* | tail -n 1 2>/dev/null`;
    $str =~ /^(\d+)/;
    $client_recspace = $1;
    print "Client $clientid has used $client_recspace of $max_record\n";
  }
}

要清楚,如果有任何以XXXX开头的文件夹,我想输入if语句。

希望这是有道理的!感谢

2 个答案:

答案 0 :(得分:5)

您可以使用glob展开通配符:

for my $dir (grep -d, glob "$monitor_location/$clientid*") {
   ...
}

答案 1 :(得分:1)

我对glob有一个“东西”。 (它似乎只能工作一次(对我来说),这意味着你不能在同一个剧本中再次对同一个目录进行重新计算。不过,它可能只是我。)

我更喜欢readdir()。这肯定更长,但它是WFM。

chdir("$monitor_location") or die;
open(DIR, ".") or die;
my @items = grep(-d, grep(/^$clientid/, readdir(DIR)));
close(DIR);

@items中的所有内容都符合您的要求。

相关问题