Perl
一起列印兩個標籤的屬性
我正在
XML:twig
使用 Perl 從 XML 文件中提取一些屬性;這是我的程式碼:
use XML::Twig; my $file = $ARGV[0]; $file =~ /(.+)\.xml/; my $outfile = $1.".snp" ; open my $out,'>',$outfile or die "Could not open file '$outfile' $!"; my $twig = XML::Twig->new ( twig_handlers => { 'Rs/MergeHistory' => \&MergeHistory, } ); $twig -> parsefile( "$file"); sub MergeHistory { my ($twig, $elt) = @_; print $out "\t"; print $out "rs"; print $out $elt->att('rsId'), ","; print $out "b"; print $out $elt->att('buildId'), ","; }
這將列印以下結果:
rs56546490,b130, rs386588736,b142 rs56546490,b130, rs386588736,b142
我想要的是將每個列印在一起
MergeHistory
rsId
,buildId
如下所示:rs56546490,rs386588736, b130,b142 rs56546490,rs386588736, b130,b142
這是 XML 文件的一部分:
<Rs> <MergeHistory rsId="56546490" buildId="130" /> <MergeHistory rsId="386588736" buildId="142" /> </Rs> <Rs> <MergeHistory rsId="56546490" buildId="130" /> <MergeHistory rsId="386588736" buildId="142" /> </Rs>
這:
use XML::Twig; my $file = $ARGV[0]; $file =~ /(.+)\.xml/; my $outfile = $1.".snp" ; open my $out,'>',$outfile or die "Could not open file '$outfile' $!"; my $twig = XML::Twig->new ( twig_handlers => { 'Rs/MergeHistory' => \&MergeHistory, } ); # Here starts changed code. my %output = ( "rs", (), "b" , () ); $twig -> parsefile( "$file" ); my $inLine = 2; # You said You want 2 in one line. while( @{$output{"rs"}} ) { for( my $i=0; $i < $inLine; $i++ ) { print "rs" . ( shift @{$output{"rs"}} ) . ","; } print "\t"; for( my $i=0; $i < $inLine; $i++ ) { print "b" . ( shift @{$output{"b"}} ) . ( $i == $inLine-1 ? "" : "," ); } } print "\n"; sub MergeHistory { my ($twig, $elt) = @_; push @{$output{"rs"}}, ( "rs" . $elt->att('rsId') ); push @{$output{"b"}}, ( "b" . $elt->att('buildId') ); }
將列印這個:
rs56546490,rs386588736, b130,b142