Re: [問題] 重複性的資料

看板Perl作者 (reputation)時間17年前 (2007/08/21 21:17), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串4/4 (看更多)
※ 引述《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
一律將 $hash{$str} chomp之後再印 印的時候\n
08/21 21:18, 1F
文章代碼(AID): #16okNlDU (Perl)
文章代碼(AID): #16okNlDU (Perl)