如何从以下代码和数据创建数组哈希:
这是我的密码:
use strict;
use warnings;
use Data::Dumper;
my %hash;
while(<DATA>) {
chomp;
my $line = $_;
print "$line\n";
my ($id) = /^(track.*$)/;
my ($mem) = /^(chr22.*$)/;
print " ID: $id - $mem\n";
push @{$hash{$id}},$mem;
}
print Dumper \%hash;
__DATA__
track name=chr22[Target-Scrambled-Inversion]_29112_INS_-263
chr22[Target-Scrambled-Inversion] 29835 30134
chr22[Target-Scrambled-Inversion] 29154 29453
track name=chr22[Target-Scrambled-Inversion]_30604_INV_8872
chr22[Target-Scrambled-Inversion] 29141 29440 因此,每个元素都有散列track作为键,随后的chr22条目作为其成员。
最后,我想创建这个输出:
$VAR = [ "track name=chr22[Target-Scrambled-Inversion]_29112_INS_-263" =>
["chr22[Target-Scrambled-Inversion] 29835 30134",
"chr22[Target-Scrambled-Inversion] 29154 29453"],
"track name=chr22[Target-Scrambled-Inversion]_30604_INV_8872" =>
["chr22[Target-Scrambled-Inversion] 29141 29440" ]];当前执行失败:https://eval.in/89547
发布于 2014-01-15 07:53:05
您在您想要的输出数组括号[,]中为您的散列编写了代码。
试试这个:
use strict;
use warnings;
my %hash;
my $track_chr = 0;
while( my $line = <DATA>) {
chomp $line;
if ($line =~ m/^track/) {
$track_chr = $line;
#$hash->{$line};
}
if ($track_chr && $line =~ m/^chr/) {
push @{$hash{$track_chr}},$line;
}
}
print Dumper \%hash;
__DATA__
track name=chr22[Target-Scrambled-Inversion]_29112_INS_-263
chr22[Target-Scrambled-Inversion] 29835 30134
chr22[Target-Scrambled-Inversion] 29154 29453
track name=chr22[Target-Scrambled-Inversion]_30604_INV_8872
chr22[Target-Scrambled-Inversion] 29141 29440 很简单。输出:
$VAR1 = {
'track name=chr22[Target-Scrambled-Inversion]_29112_INS_-263 ' => [
'chr22[Target-Scrambled-Inversion] 29835 30134 ',
'chr22[Target-Scrambled-Inversion] 29154 29453 '
],
'track name=chr22[Target-Scrambled-Inversion]_30604_INV_8872' => [
'chr22[Target-Scrambled-Inversion] 29141 29440 '
]
};发布于 2014-01-15 07:58:45
你可以这样做..。
use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Indent = 1; # personal preference for readability
my %hash;
my $key;
# iterate over a line at a time
while ( my $line = <DATA> ) {
chomp $line;
# if the line begins with "track" store the key
if ($line =~ /^track/) {
$key = $line;
} elsif ($line =~ /^chr22/) {
# skip this line if we were not able to set a key...
next if !defined $key;
# else we push onto the array
push @{$hash{$key}}, $line;
}
}
print Dumper \%hash;
__DATA__
track name=chr22[Target-Scrambled-Inversion]_29112_INS_-263
chr22[Target-Scrambled-Inversion] 29835 30134
chr22[Target-Scrambled-Inversion] 29154 29453
track name=chr22[Target-Scrambled-Inversion]_30604_INV_8872
chr22[Target-Scrambled-Inversion] 29141 29440
some random line
more randomnessssssss产出:
$ perl test.pl
$VAR1 = {
'track name=chr22[Target-Scrambled-Inversion]_29112_INS_-263 ' => [
'chr22[Target-Scrambled-Inversion] 29835 30134 ',
'chr22[Target-Scrambled-Inversion] 29154 29453 '
],
'track name=chr22[Target-Scrambled-Inversion]_30604_INV_8872' => [
'chr22[Target-Scrambled-Inversion] 29141 29440 '
]
};https://stackoverflow.com/questions/21131598
复制相似问题