一起打印两个标签的属性

一起打印两个标签的属性

我正在使用XML:twigPerl 从 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 rsIdbuildId一起打印如下:

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>

答案1

这:

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

相关内容