源文内容格式如下:
中文12345678 中文11111111 中文字符1
中文23456781 中文11111111 中文字符1
.......
中文12345678 中文22222222 中文11111111 中文字符2
中文23456781 中文22222222 中文11111111 中文字符2
目标文件内容如下(替换后的)
中文11111111 中文字符1
中文22222222 中文字符2
老师, 请教下,用perl 语言,把一个文件里面的一部分内容写到另一个文件里的方法。谢谢!
答案:2 悬赏:40 手机版
解决时间 2021-03-19 00:23
- 提问者网友:活着好累
- 2021-03-18 19:19
最佳答案
- 五星知识达人网友:往事隔山水
- 2021-03-18 20:08
根据我的理解,做了一个脚本,在我的机器上试过了:
use 5.016;
use warnings;
use utf8;
use autodie;
my %target;
my $source_file = 'original.txt';
my $target_file = 'target.txt';
my $source_file_fh; # your source file handle
my $target_file_fh; # your target file handle
my $key; # key item in target file
my $content; # last content item in target file
sub get_last_item {
my $str = shift;
$str =~ /.*[ ]+(.*)/;
return $1;
}
sub get_key {
my $str = shift;
my $content = shift;
$str =~ /.*[ ]+(.*)[ ]+$content/;
return $1;
}
open($source_file_fh, "<", $source_file);
open($target_file_fh , ">", $target_file);
while (<$source_file_fh>) {
$content = get_last_item($_);
$key = get_key($_, $content);
$target{$key} = $content if ($key);
}
for (sort keys %target) {
say $target_file_fh "$_ $target{$_}";
}
close $target_file_fh;
close $source_file_fh;
use 5.016;
use warnings;
use utf8;
use autodie;
my %target;
my $source_file = 'original.txt';
my $target_file = 'target.txt';
my $source_file_fh; # your source file handle
my $target_file_fh; # your target file handle
my $key; # key item in target file
my $content; # last content item in target file
sub get_last_item {
my $str = shift;
$str =~ /.*[ ]+(.*)/;
return $1;
}
sub get_key {
my $str = shift;
my $content = shift;
$str =~ /.*[ ]+(.*)[ ]+$content/;
return $1;
}
open($source_file_fh, "<", $source_file);
open($target_file_fh , ">", $target_file);
while (<$source_file_fh>) {
$content = get_last_item($_);
$key = get_key($_, $content);
$target{$key} = $content if ($key);
}
for (sort keys %target) {
say $target_file_fh "$_ $target{$_}";
}
close $target_file_fh;
close $source_file_fh;
全部回答
- 1楼网友:夜余生
- 2021-03-18 20:20
不知道什么原因,今天我发的回答都显示不出来,只能用匿名发送试试看。(jasonqwu)
做了一个脚本,在我的机器上试过了:
use 5.016;
use warnings;
use utf8;
my %target;
my $source_file = 'original.txt';
my $target_file = 'target.txt';
my $source_file_fh; # your source file handle
my $target_file_fh; # your target file handle
my $key; # key item in target file
my $content; # last content item in target file
open($source_file_fh, ":utf8", $target_file) or die "can't open $target_file : $!\n";
while (<$source_file_fh>) {
$content = get_last_item($_);
$key = get_key($_, $content);
$target{$key} = $content if ($key);
}
for (sort keys %target) {
say $target_file_fh "$_ $target{$_}";
}
close $target_file_fh;
close $source_file_fh;
sub get_last_item {
my $str = shift;
$str =~ /.*[ ]+(.*)/;
return $1;
}
sub get_key {
my $str = shift;
my $content = shift;
$str =~ /.*[ ]+(.*)[ ]+$content/;
return $1;
}按照新的要求,修改了代码,请确认。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯