2012-07-25 100 views
1

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

在我的脚本中,我有两个变量$ 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语句。

希望这是有道理的!由于

回答

5

您可以使用glob扩大通配符:

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

我已经编辑了问题中的代码,以更好地展示我想实现的目标。想知道如何将上面的代码嵌入到我的代码中,会感激不小的输入吗?谢谢 – btongeorge 2012-07-26 09:03:34

+0

好的解决方案和良好的'grep'使用方法 – gaussblurinc 2012-07-26 09:12:17

+0

@btongeorge:如果你只是想知道这些目录是否存在,你可以使用'if(grep -d,glob“$ ...”)''。 – choroba 2012-07-26 09:26:44

1

我有一个“东西”反对水珠。 (它似乎只能工作一次(对我来说),这意味着你不能在同一个脚本中重新使用同一个目录,但这可能只是我自己。)

我更喜欢readdir()。这绝对是更长的时间,但它WFM。

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

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

+0

有道理,谢谢。因此,把它放在我的原始代码的上下文中,我需要运行du线来获取具有相同客户端ID的所有目录的组合大小,以便@items中的每个ID。我怎么能这样做呢? – btongeorge 2012-07-25 17:04:02

+1

@jimtut:'glob'在标量上下文中创建一个迭代器。这可能是你失败的根源。 – choroba 2012-07-25 17:17:04

+0

'glob'通常是DWIM,但它有它的特质和不直观的用途。记住非'glob'解决方案是很好的。 – mob 2012-07-26 17:06:32

相关问题