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