use strict;
use warnings;
my %result_hash =();
my %final_hash =();
Compare_results();
foreach my $key (sort keys %result_hash){
print "$key \n";
print "$result_hash{$key} \n";
}
sub Compare_results
{
while (<DATA>)
{
my($instance,$values) = split /\:/, $_;
$result_hash{$instance} = $values;
}
}
__DATA__
1:7802315095\d\d,7802315098\d\d;7802025001\d\d,7802025002\d\d,7802025003\d\ d,7802025004\d\d,7802025005\d\d,7802025006\d\d,7802025007\d\d
2:7802315095\d\d,7802025002\d\d,7802025003\d\d,7802025004\d\d,7802025005\d\d,7802025006\d\d,7802025007\d\d
1
7802315095\d\d,7802315098\d\d;7802025001\d\d,7802025002\d\d,7802025003\d\d,7802025004\d\d,7802025005\d\d,7802025006\d\d,7802025007\d\d
2
7802315095\d\d,7802025002\d\d,7802025003\d\d,7802025004\d\d,7802025005\d\d,7802025006\d\d,7802025007\d\d
蔭試圖獲取每個鍵的值,然後再次嘗試從結果哈希分裂逗號分隔值,如果我發現任何值我會分號想要將左值和右值存儲在單獨的哈希鍵中。
類似下面
1.#split the value of result_hash{$key} again by , and see whether any chunk is seperated by ;
2. #every chunk without ; and value on left with ; should be stored in
@{$final_hash{"eto"}} = ['7802315095\d\d','7802315098\d\d','7802025002\d\d','7802025003\d\d','7802025004\d\d','7802025005\d\d','7802025006\d\d','7802025007\d\d'] ;
3.#Anything found on the right side of ; has to be stored in
@{$final_hash{"pro"}} = ['7802025001\d\d'] ;
有,我可以處理子程序中的一切呢?我可以讓代碼更簡單
更新:
我想在一個單杆分割字符串,但它只是挑選與分號的值,而忽略一切
foreach my $key (sort keys %result_hash){
# print "$key \n";
# print "$result_hash{$key} \n";
my ($o,$t) = split(/,|;/, $result_hash{$key});
print "Left : $o \n";
print "Left : $t \n";
#push @{$final_hash{"eto"}}, $o;
#push @{$final_hash{"pro"}} ,$t;
}
}
我幫助後更新的代碼
sub Compare_results
{
open my $fh, '<', 'Data_File.txt' or die $!;
# split by colon and further split by , and ; if any (done in insert_array)
my %result_hash = map { chomp; split ':', $_ } <$fh> ;
foreach (sort { $a <=> $b } (keys %result_hash))
{
($_ < 21)
? insert_array($result_hash{$_}, "west")
: insert_array($result_hash{$_}, "east");
}
}
sub insert_array()
{
my ($val,$key) = @_;
foreach my $field (split ',', $val)
{
$field =~ s/^\s+|\s+$//g; #/turn off editor coloring
if ($field !~ /;/) {
push @{ $file_data{"pto"}{$key} }, $field ;
}
else {
my ($left, $right) = split ';', $field;
push @{$file_data{"pto"}{$key}}, $left if($left ne '') ;
push @{$file_data{"ero"}{$key}}, $right if($right ne '') ;
}
}
}
感謝
很好的想法,但是如果拆分的是'/ [;] /'你怎麼說哪些是「正確的」(「;」)?它以任意順序返回所有字段的列表,無論是「,」還是「;」。 (你寫的內容將列表分配給兩個(2)標量,所以你只能得到分割後的前兩個元素。) – zdim
我編輯了你的添加 - 將長註釋移動到它自己的行,所以不必滾動閱讀它,並通過正則表達式添加了一個評論'#/ ...',這個編輯器關閉了錯誤的紅色着色。 (它經常這樣做 - 在一個正則表達式之後,一切都變成紅色。)如果你不喜歡這個,請恢復更改 - 點擊我的用戶名上面的「編輯(時間)」,你會看到修訂版本,每個版本都有按鈕。其中一個說「回滾」,點擊你想要回滾的修訂版本。 – zdim
@zdim:你會讓我知道如何分割有兩個分隔符的數據:1,2,3,4,5,6,7; 8,9,10,11,12,我想存儲所有的東西之後;在一個數組中,在另一個數組中。請用一杆分裂功能幫助我。 O/P array1 = [1,2,3,4,5,6,7]和array2 = [8,9,10,11,12] – LearningCpp