首页 > 解决方案 > 匹配哈希之间的某些单词行

问题描述

我试图在两个文件之间匹配这个电话号码,我在堆栈流中找到了这个代码;比较文件行以匹配第二个文件中的任何位置

    use strict;   #ALWAYS ALWAYS ALWAYS
    use warnings; #ALWAYS ALWAYS ALWAYS

    use autodie;  #Will end the program if files you try to open don't exist

    # Constants are a great way of storing data that is ...uh... constant
    use constant {
        FILE_1    =>  "a1.txt",
        FILE_2    =>  "a2.txt",
    };

my %phone_hash1;
my %phone_hash2;

open my $phone_num1_fh, "<", FILE_1;

while ( my $phone_num = <$phone_num1_fh> ) {
    chomp $phone_num;
    $phone_hash1{ $phone_num } = 1;
}
close $phone_num1_fh;

open my $phone_num2_fh, "<", FILE_2;

while ( my $phone_num = <$phone_num2_fh> ) {
    chomp $phone_num;
    $phone_hash2{ $phone_num } = 1;
}
close $phone_num2_fh;

my %in_common;

for my $phone ( keys %phone_hash1 ) {
    if ( $phone_hash2{$phone} ) { 
       $in_common{$phone} = 1;    #Phone numbers in common between the two lists
    }
}
for my $phone ( sort keys %phone_hash1 ) {
    if ( not $in_common{$phone} ) {
         print "Phone number $phone is only in the first file\n";
    }
}

for my $phone ( sort keys %phone_hash2 ) {
    if ( not $in_common{$phone} ) {
        print "Phone number $phone is only in " . FILE_2 . "\n";
    }
}

for my $phone ( sort keys %in_common ) {
    print "Phone number $phone is in both files\n";
}

问题是; 在我的第一个文件中,我需要过滤掉电话号码,所以,我试着做这个;

 if ($s1 =~ m/(.*)\s+(.*)\s+(.*)\s+/) 
        {
        my $phone_num=($1."/".$2);
        chomp $phone_num;
        $phone_hash1{ $phone_num } = 1;
        }

我的第二个文件在电话号码前面有一个路径,例如 alias/a/b/c/ 0123456789

而且我不知道如何将这个过滤到哈希中,或者过滤掉我不想要的东西,这样我就可以在两个文件之间比较这两个数字。

($phone_hash2{ $phone_num }  =~ /.*$str/)

标签: perl

解决方案


如果前缀在“第二个文件”的内容中始终相同

alias/a/b/c/${phone_number_1}
alias/a/b/c/${phone_number_2}
alias/a/b/c/${phone_number_3}

然后可以通过以下方式删除前缀substr

my $offset = length("alias/a/b/c/");
while(my $line = <$fh_file>) { 
    chomp($line);
    $line = substr($line, $offset);
}

如果它不是相同的前缀,因为您提到它们看起来像“路径”,我将假设该路径的最后一部分是实际的电话号码。所以解决方案很简单:走路径的最后一部分。这也是“在/$line 末尾没有任何内容的最长子字符串”(假设与上述相同的 while 循环结构):

my ($phone) = $line =~ m{([^/]+)\z};

或者,从不同的角度来看:“从 $line 中删除以 a/结尾的最长前缀,而不是取 $line 的其余部分”:

my $phone = $line =~ s{\A.+/}{}r;

当然,如果电话号码本身可以用一个简单的模式来枚举,例如,[0-9]{8}(从 8 个字符的集合中[0123456789]),也许更直接的方法是“将锚定在 $line 末尾的部分与电话号码匹配图案”:

my ($phone) = $line =~ m{([0-9]{8})\z};

如果以上都没有涵盖您的情况,那么......我只是不擅长猜测:)


推荐阅读