Re: [問題] 重複性的資料
※ 引述《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
→
08/21 21:18, , 1F
08/21 21:18, 1F
討論串 (同標題文章)