作者roy8130 (reputation)
看板perl
标题Re: [问题] 重复性的资料
时间Tue Aug 21 21:17:34 2007
※ 引述《salagadoola (南瓜)》之铭言:
: ※ 引述《roy8130 (reputation)》之铭言:
: : 当重复遇到X=24 & Y=1时候 把更新的 value , 覆盖到第一个
: : X=24 & Y=1的位置
: : 每ㄧ个集合为 {
: : X=24
: : Y=1
: : 14
: : 2
: : 6
: : 30
: : }
: : test.txt ------------------------> output results
: open FH, "<", "test.txt";
: my $str = join("", <FH>);
: close FH;
: my %hash; ## 存放资料,以 X=...\nY=...\n 为 key
: my @arr; ## 纪录每一个 key 出现的前後顺序
: while ( $str =~ s/(X=\d+\nY=\d+\n)([^X]+)// ) {
: if ( not exists $hash{$1} ) {
: push @arr, $1; ## 遇到没看过的 key 就放进 @arr 里
: }
: $hash{$1} = $2;
: }
: foreach my $str (@arr) {
: print $str, $hash{$str};
: }
: 注:这里用 X 来判断资料间的分隔,所以如果 value 里有 X 的话程式就会错。
use strict;
open FH, "<", "test.txt";
my $str = join("", <FH>);
close FH;
my %hash;
my @arr;
while ( $str =~ s/(X=\d+\nY=\d+\n)([^X]+)// ) {
if ( not defined $hash{$1} ) {
push @arr, $1;
}
$hash{$1} = $2;
}
foreach my $str (@arr) {
print $str, $hash{$str};
}
results:
X=24
Y=1
11
2
6
9
30 X=23
Y=1
14
25
28
29
30
X=22
Y=1
14
25
26
29
30
感觉X=23少一个\n
如果print $str, $hash{$str}; 改成print $str, $hash{$str}, "\n";
就会变成多一个空格
X=24
Y=1
11
2
6
9
30
X=23
Y=1
14
25
28
29
30
X=22
Y=1
14
25
26
29
30
请问要如何做笔较好呢?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.216.112.8
1F:→ LiloHuang:一律将 $hash{$str} chomp之後再印 印的时候\n 08/21 21:18