1

I am using XML:twig to extract some attributes from an XML file using Perl;

Here is my code:

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

This print the following results:

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

What I want is to print each MergeHistory rsId and buildId together as the following:

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

Here is a part of the XML file:

<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
  • you want to print all of the rsIds at the start of the line, then a tab, and then all of the buildIds? no matter how many of them there are?
    – cas
    Sep 21, 2015 at 21:54

1 Answer 1

0

This:

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

Will print this:

rs56546490,rs386588736,   b130,b142
2
  • 1
    thanks it works, but if I have 4 tags and want to print the values of each two rsId and buildId on one line and the values of next two on new line Sep 21, 2015 at 23:15
  • @AhmedMahdi, I've edited my answer. $inLine sets how much values you want in line.
    – Marqin
    Sep 22, 2015 at 14:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .