2013-12-18 66 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