【发布时间】:2020-05-26 22:22:45
【问题描述】:
所以我想弄清楚如何替换特定列中的数字并将该数字替换为字母。我正在用 Perl 编码
input.txt
10004226549870
204226549870062001186000000000040008060802
5032000067470318021604226549870062001186
603200100001312293000522105000000456000131289
603200200006545553000522109000004242000654555
603200300002463923000522090000005571000246392
603200400002635413000521196000248920000263541
60320050000175960300052196600000101700017596
603200600001054853004867190000001003000105485
603200700001451223000522095000003981000145122
75030000674703180216000700017222840007
89999990674703180216000070001722284
9000013
替换表
1 -> A
2 -> B
3 -> C
4 -> D
5 -> E
6 -> F
7 -> G
8 -> H
9 -> I
0 -> {
替换应在以下情况下发生:
Line starts with a "6", for the numbers located in column 17 and column 45.
Line starts with a "7", for the number located in column 34.
Line starts with a "8", for the number located in column 35.
通过上述替换规则,生成的文件(使用当前文件作为 一个例子),会导致:
output.txt
10004226549870
2042265498700620
5032000067470318021604226549870062001186
6032001000013122I3000522105000000456000131289
6032002000065455E3000522109000004242000654555
6032003000024639B3000522090000005571000246392
6032004000026354A3000521196000248920000263541
6032005000017596{300052196600000101700017596
6032006000010548E3004867190000001003000105485
6032007000014512B3000522095000003981000145122
750300006747031802160007000172228D0007
8999999067470318021600007000172228D
9000013
**我的代码
my $fn = 'input.txt';
my $wr = 'output.txt';
my %repl = (
1 => "A"
2 => "B"
3 => "C"
4 => "D"
5 => "E"
6 => "F"
7 => "G"
8 => "H"
9 => "I"
0 => "{"
);
open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
open ( my $ww, '>', $wr ) or die "Could not open file '$fn': $!";
my @lines;
while (my $line = <$fh>) {
chomp $line;
push @lines, $line;
if ( $line =~ /^6/) {
foreach my $key (sort keys %repl){
substr($line, 17, 1) =~ s/\b$key\b/$repl{$key}/g
substr($line, 45, 1) =~ s/\b$key\b/$repl{$key}/g
}
}
elsif ($line =~ /^7/) {
foreach my $key (sort keys %repl){
substr($line, 34, 1) =~ s/\b$key\b/$repl{$key}/g
}
}
elsif ($line =~ /^8/) {
foreach my $key (sort keys %repl){
substr($line, 35, 1) =~ s/\b$key\b/$repl{$key}/g
}
}
else {
print $ww $_;
}
}
close $fh;
close $ww;
【问题讨论】:
-
预期的
output.txt不会在位置 45 处显示以 6 开头的数字的替换...这只是一个提示吗?然后,将{作为替换的行(在 17 处)没有 45 个字符,而是 44 个字符——那该怎么办,什么也不做或添加一个字符?
标签: perl