Imprime atributos de duas marcas juntas

1

Estou usando XML:twig para extrair alguns atributos de um arquivo XML usando Perl;

Aqui está o meu código:

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'), ",";
    }

Imprima os seguintes resultados:

rs56546490,b130,    rs386588736,b142
rs56546490,b130,    rs386588736,b142

O que eu quero é imprimir cada MergeHistory rsId e buildId juntos como segue:

rs56546490,rs386588736,   b130,b142
rs56546490,rs386588736,   b130,b142

Aqui está uma parte do arquivo 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>
    
por Ahmed Mahdi 21.09.2015 / 22:00

1 resposta

0

Isto:

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') );
    }

imprimirá isso:

rs56546490,rs386588736,   b130,b142
    
por 21.09.2015 / 23:28

Tags