【发布时间】:2018-10-11 15:09:03
【问题描述】:
我正在尝试在两个文件之间匹配此电话号码,我在堆栈流中找到了此代码; Compare file lines for match anywhere in second file
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;
}
我的第二个文件电话号码前面有一个路径 比如别名/a/b/c/0123456789
我不知道如何将这个数字过滤到哈希中,或者过滤掉我不想要的东西,以便我可以在两个文件之间比较这两个数字。
($phone_hash2{ $phone_num } =~ /.*$str/)
【问题讨论】:
-
我们可以在这里使用一些示例数据,以及您要过滤的内容的示例。
标签: perl