perl - Foreach 循环中的动态数组

标签 perl

第一次张贴者和 Perl 的新手所以我有点卡住了。我正在遍历一组长文件名,其中的列由可变数量的空格分隔,例如:

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

这些是由多个服务器生成的,因此我正在遍历多个集合。该机制非常简单。

我只关注日期列,需要确保日期像上面的示例一样更改,因为这确保文件每天创建一次,而且只创建一次。如果文件每天创建多次,我需要做一些事情,比如给自己发一封电子邮件,然后继续下一个服务器集合。如果日期从第一个文件更改为第二个文件,则也退出循环。

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

@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;
            }
}

最佳答案

一种常见的技术是使用 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
}

关于perl - Foreach 循环中的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20670262/

相关文章:

perl - 为什么 Perl 在我的 CGI 脚本中提示 "Use of uninitialized value"?

perl - 使用 DBIx::Class,如何检查表是否存在?

正则表达式替换

perl - 可以修补 File::Find::Rule 以自动处理文件名字符编码/解码吗?

xml - 在 Perl 中从 XML 文件中提取一些元素值的最快方法是什么?

perl - 在 Perl 中如何获取正在读取的文件的名称?

javascript - 向网站添加缩略图

bash - 在每个空行上拆分大文本文件

perl - 如何使用 perl 检查哪些字体包含特定字符?

perl - 分层和可继承配置的最佳 Perl 模块是什么?