2013-12-18 129 views
3

第一次海报和新的Perl,所以我有点卡住了。我通过长文件名的集合迭代由不同数量的空白,例如分离柱:Foreach循环中的动态数组

0  19933  12/18/2013 18:00:12 filename1.someextention 
1  11912  12/17/2013 18:00:12 filename2.someextention 
2  19236  12/16/2013 18:00:12 filename3.someextention 

这些都是由多个服务器生成的,所以我通过多个集合迭代。这个机制很简单。

我只关注日期列,并且需要确保日期如上面的示例那样发生变化,因为这可以确保文件每天仅创建一次。如果文件每天创建一次以上,我需要做一些事情,比如发邮件给自己,然后转到下一个服务器集合。如果日期从第一个文件更改为第二个退出循环。

我的问题是我不知道如何保留第一个文件的日期元素存储,以便我可以将它与通过循环的下一个文件的日期进行比较。我想过把元素存储在循环内的数组中,直到当前的集合完成,然后转移到下一个集合,但我不知道这样做的正确方法。任何帮助将不胜感激。另外,如果有一种更有说服力的方式,请启发我,因为我愿意学习,而不只是想让别人为我写剧本。

@file = `command -h server -secFilePath $secFilePath analyzer -archive -list`; 
@array = reverse(@file); # The output from the above command lists the oldest file first 

    foreach $item (@array) { 
    @first = split (/ +/, @item); 
    @firstvar = @first[2]; 
#if there is a way to save the first date in the @firstvar array and keep it until the date 
changes  
    if @firstvar == @first[2] { # This part isnt designed correctly I know.    } 
      elsif @firstvar ne @first[2]; { 
      last; 
      } 
} 

回答

3

一种常用的技术是使用一个hash,这是一个数据结构的映射的键 - 值对。如果您按日期键入,则可以检查之前是否遇到过某个日期。

如果没有遇到日期,它在散列中没有密钥。

如果遇到一个日期,我们在该键下插入1来标记它。

my %dates; 
foreach my $line (@array) { 
    my ($idx, $id, $date, $time, $filename) = split(/\s+/, $line); 

    if ($dates{$date}) { 
     #handle duplicate 
    } else { 
     $dates{$date} = 1; 

     #... 
     #code here will be executed only if the entry's date is unique 
    } 

    #... 
    #code here will be executed for each entry 
} 

请注意,这将检查每个日期对每个其他日期。如果由于某种原因,你只想检查两个相邻日期是否匹配,你可以缓存最后的$date并检查。


在评论中,OP提到他们可能会执行我提到的第二次检查。它是相似的。可能是这样的:

#we declare the variable OUTSIDE of the loop 
#if needs to be, so that it stays in scope between runs 
my $last_date; 
foreach my $line (@array) { 
    my ($idx, $id, $date, $time, $filename) = split(/\s+/, $line); 

    if ($date eq $last_date) { #we use 'eq' for string comparison 
     #handle duplicate 
    } else { 
     $last_date = $date; 

     #... 
     #code here will be executed only if the entry's date is unique 
    } 

    #... 
    #code here will be executed for each entry 
} 
+0

我认为你需要注意的是沿着什么,我需要做的线条更....我需要缓存的第一日期的引用,所以我可以把它比作从第二日起参考数组中的下一条记录。我怎么能这样做? – Capitalismczar

+0

我在我的答案中添加了一些示例代码。 – rutter

+0

它不会工作,因为我甚至没有从文件名中提取日期,直到将行分割到数组中。我不是在用实际的日期工作,而是在日期的文本输出中......知道我的意思吗? – Capitalismczar