【问题标题】:Perl : matching the contents of a file with the contents of an arrayPerl:将文件的内容与数组的内容相匹配
【发布时间】:2016-01-08 10:23:15
【问题描述】:

我有一个数组@arr1,其中每个元素的格式为#define A B

我有另一个文件,f1,内容如下:

#define,x,y
#define,p,q

等等。我需要检查每行的第二个值(yq 等)是否与数组的任何元素中的第一个值匹配。示例:假设数组有一个元素#define abc 123,文件有一行#define,hij,abc

当出现这样的匹配时,我需要将行 #define hij 123 添加到数组中。

while(<$fhDef>)               #Reading the file
{
    chomp;
    $_ =~ tr/\r//d;
    if(/#define,(\w+),(\w+)/)
    {
        my $newLabel = $1;
        my $oldLabel = $2;
        push @oldLabels, $oldLabel;
        push @newLabels, $newLabel;
    }
}

      foreach my $x(@tempX)             #Reading the array
      {
            chomp $x;
            if($x =~ /#define\h{1}\w+\h*0x(\w+)\h*/)
            {
                my $addr = $1;
                unless(grep { $x =~ /$_/ } @oldLabels) 
                {
                    next;
                }
                my $index = grep { $oldLabels[$_] eq $_ } 0..$#oldLabels;
                my $new1 = $newLabels[$index];
                my $headerLabel1 = $headerLabel."X_".$new1;
                chomp $headerLabel1;
                my $headerLine = "#define ".$headerLabel1."0x".$addr;
                push @tempX, $headerLine;
            }
         }

这只是挂起。毫无疑问,我错过了眼前的一些东西,但是什么??

【问题讨论】:

    标签: arrays regex perl file-io


    【解决方案1】:

    规范的方法是使用哈希。散列数组,使用第一个参数作为键。然后遍历文件并检查哈希中是否存在密钥。我使用 HoA(数组哈希)来处理每个键的多个值(参见最后两行)。

    #! /usr/bin/perl
    use warnings;
    use strict;
    
    my @arr1 = ( '#define y x',
                 '#define abc 123',
               );
    
    my %hash;
    for (@arr1) {
        my ($arg1, $arg2) = (split ' ')[1, 2];
        push @{ $hash{$arg1} }, $arg2;
    }
    
    while (<DATA>) {
        chomp;
        my ($arg1, $arg2) = (split /,/)[1, 2];
        if ($hash{$arg2}) {
            print "#define $arg1 $_\n" for @{ $hash{$arg2} };
        }
    }
    
    __DATA__
    #define,x,y
    #define,p,q
    #define,hij,abc
    #define,klm,abc
    

    【讨论】:

    • 感谢您提供优雅的解决方案。
    【解决方案2】:

    正如另一个答案所说,最好使用哈希。另外,请记住,您正在做一个

    foreach my $x(@tempX)
    

    但你也在做一个

    push @tempX, $headerLine;
    

    这意味着您正在修改您正在迭代的数组。这不仅是不好的做法,这也意味着您很可能会因此而陷入无限循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多