当我有2个文本时,如何在Perl中替换?

时间:2016-06-06 20:17:48

标签: perl

我有2个文件,第一个有2行:第一行是整数,第二行是字符串。第二个文件是带有相应编号的字符串,我想用文件2中的相应编号替换文件1中的字符串(如文件2之后的输出文件):

文件1:

KARD 28.5581  51.6588 
CHAH 28.4683  51.6566 
SANA 28.4513  51.6041

我想替换一个数字而不是字符串:

文件2:

51.6659  28.4185
28.4683  51.6566
--- 
51.6659  28.4185
28.4513  51.6041

我想要的是:

输出:

{{1}}

1 个答案:

答案 0 :(得分:1)

尝试这个程序,也许它会给出如何开始的想法。

有关Perl基础知识的更多信息:https://www.perl.org/books/beginning-perl/

#!/usr/bin/perl
# test.pl

use strict;
use warnings;

# 1. Assign the files
my $file1 = './file1.txt';
my $file2 = './file2.txt';

# 2. Read the files
my @file1_arr;
open(my $fh, "<", $file1) or die "Can't open $file1: $!";
while (my $row = <$fh>) {
  chomp $row;
  push(@file1_arr, $row);
}
close($fh);

my @file2_arr;
open(my $fh2, "<", $file2) or die "Can't open $file2: $!";
while (my $row = <$fh2>) {
  chomp $row;
  push(@file2_arr, $row);
}
close($fh2);

# 3. Replace string in file1 with corresponding number in file 2
# create a look up table from @file2_arr
my %name_ha;
foreach my $i (@file2_arr) {
    my @arr = split(/\s+/,$i);
    my $key = $arr[0] . 'P'; # modify from CHAH to CHAHP...
    my $value = "$arr[1] $arr[2]";
    $name_ha{$key} = $value;
}

# replace...
my @str_arr = split(/\s+/, $file1_arr[1]); # CHAHP SANAP
my @str_res;
foreach my $i (@str_arr) {
    push(@str_res, $name_ha{$i}) if (defined $name_ha{$i}); 
}

# print result
my $res;
foreach my $i (@str_res) { 
    $res .= "$file1_arr[0]\n";
    $res .= "$i\n---\n";
}
print $res;

# 4. Write result into a new file
open(my $fh3, ">", "./output.txt") or die "Can't open > ./output.txt: $!";
print $fh3 $res;
close($fh3);

print "Result saved in ./output.txt\n";

# output: 
# [~]$ ./test.pl
# 51.6659 28.4185
# 28.4683 51.6566
# ---
# 51.6659 28.4185
# 28.4513 51.6041
# ---
# Result saved in ./output.txt
# [~]$ cat ./output.txt
# 51.6659 28.4185
# 28.4683 51.6566
# ---
# 51.6659 28.4185
# 28.4513 51.6041
# ---
# [~]$