【问题标题】:glob skipping files [duplicate]glob跳过文件[重复]
【发布时间】:2011-08-25 07:40:02
【问题描述】:

可能重复:
Why does Perl's glob return undef for every other call?

这是我遇到的另一个问题的延续,我需要找到一个名称很长但我知道名称的一部分的文件,这是我使用的代码:

my @RTlayerRabcd = ("WIRA_Rabcd_RT","WIRB_Rabcd_RT","WIRC_Rabcd_RT","WIRD_Rabcd_RT","WIRE_Rabcd_RT","BASE_Rabcd_RT");

#Rabcd calculations
for($i = 0; $i < 6; $i++) 
{
    print "@RTlayerRabcd[$i]\n";
    #Searching for Rabcd Room Temperature readings
    my $file = glob($dir . "*@RTlayerRabcd[$i]" . '.txt');
    print "$file\n";
    my $Rtot = 0;
    #Open file, Read line
    open (FILE, $file);
    while (<FILE>)
    {
        #read line and and seperate at "tab" into $temp, $Res 
        chomp;
         ($Res, $temp) = split("\t");   
        $j++;
        $Rtot=$Res+$Rtot;

     }
     close (FILE);

    $Ravg = $Rtot/$j;
    print FILE_OUT "$Ravg \t";



 }

运行代码后,我得到以下打印输出:

WIRA_Rabcd_RT                                                               
Vesuvious_C6R8_051211/vesu_R6C8_05112011_WIRA_Rabcd_Rt.txt
WIRB_Rabcd_RT

WIRC_Rabcd_RT                                                      
Vesuvious_C6R8_051211/vesu_R6C8_05112011_WIRC_Rabcd_Rt.txt                            
WIRD_Rabcd_RT                                                

WIRE_Rabcd_RT                                                   

BASE_Rabcd_RT                                             
Vesuvious_C6R8_051211/vesu_R6C8_05112011_BASE_Rabcd_Rt.txt

程序似乎在跳过文件,知道为什么吗?

【问题讨论】:

  • 使用严格和警告,对你的open() 使用条件,然后你可能会得到一些信息。显然,glob 找不到该文件。还。 $array[0],而不是@array[0],是引用数组元素的方式。

标签: perl file search loops glob


【解决方案1】:

在标量上下文中,glob 遍历与 glob 匹配的所有文件,在最后一个之后返回 undef。它旨在用作while 循环中的条件,例如:

while (my $file = glob('*.c')) {
  say $file;
}

迭代器与对glob 的特定调用相关联。一旦迭代开始,就无法提前重置迭代器。 glob 忽略它的参数,直到它返回 undef

您可以通过在列表上下文中使用glob 来解决您的问题:

my ($file) = glob($dir . "*@RTlayerRabcd[$i]" . '.txt');

【讨论】:

  • 或者使用glob 获取一堆文件,然后使用grep 获取正确的文件。
  • 非常感谢这一切都很好。
【解决方案2】:

我的猜测是 Vesuvious_C6R8_051211 目录不包含文件 *WIRB_Rabcd_RT.txt、*WIRD_Rabcd_RT.txt 和 *WIRE_Rabcd_RT.txt。该目录的文件列表是什么?另外,我建议您检查open() 的返回码,以确保它确实成功打开了一个文件。

【讨论】:

  • 不,这是因为他在标量上下文中调用glob,而不是作为循环条件。
猜你喜欢
  • 2016-05-06
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
相关资源
最近更新 更多