Reputation: 25
So I have this code in perl that parses an xml and i want the perl file to print out to the text file so that everything is in columns like so:
SpectrumIndex TotalIonCount Duration Spectrum
Integer Float Float mass,abundance;mass1,abundance1;mass 2,abundance1
Here is the xml code:
<message>
<cmd id="result_data">
<result-file-header>
<path>String</path>
<duration>Float</duration>
<spectra-count>Integer</spectra-count>
</result-file-header>
<scan-results count="Integer">
<scan-result>
<spectrum-index>Integer</spectrum-index>
<time-stamp>Integer</time-stamp>
<tic>Float</tic>
<start-mass>Float</start-mass>
<stop-mass>Float</stop-mass>
<spectrum count="Integer">mass,abundance;mass1,abundance1;
mass2,abundance2;mass6,abundance6</spectrum>
</scan-result>
<scan-result>
<spectrum-index>Integer</spectrum-index>
<time-stamp>Integer</time-stamp>
<tic>Float</tic>
<start-mass>Float</start-mass>
<stop-mass>Float</stop-mass>
<spectrum count="Integer">mass3,abundance3;mass4,abundance4;
mass5,abundance5</spectrum>
</scan-result>
</scan-results>
</cmd>
</message>
However using the following perl code:
#!/usr/bin/perl-w
#example to write to text
my $file = "gapiformat.txt";
unless(open FILE, '>'.$file) {
die "\nUnable to create $file\n";
}
use strict;
use warnings;
use XML::Simple;
use Data::Dumper;
my $values= XMLin('samplegapi.xml',ForceArray => ['scan-result','result-file-header']);
my $results = $values->{'cmd'}->{'scan-results'}->{'scan-result'};
my $results1= $values->{'cmd'}->{'result-file-header'};
printf FILE ("%-s %-s %-s %s\n","SpectrumIndex","TotalIonCount","Spectrum","Duration");
for my $data (@$results) {
my $spectrum=$data->{spectrum};
for my $data1 (@$results1){
printf FILE ("%-s %-s %-s %-s\n",$data->{"spectrum-index"}, $data->{tic}, $spectrum
->{'content'},$data1->{duration});
}
}
It gives the following output to the text file:
SpectrumIndex TotalIonCount Spectrum Duration
Integer Float mass,abundance;mass1,abundance1;
mass2,abundance2;mass6,abundance6 Float
Integer Float mass3,abundance3;mass4,abundance4;
mass5,abundance5 Float
Any help is appreciated!
Upvotes: 0
Views: 197
Reputation: 48589
In modern perl:
open()
my
variables instead of bareword filehandles$!
) when things go wrong:open my $INFILE, '<', $fname
or die "Couldn't open $fname: $!";
You have to print line by line. You can't print one column and then another column.
So when you do this:
printf FILE (
"%-s %-s %-s %-s\n",
$data->{"spectrum-index"},
$data->{tic},
$spectrum->{'content'},
$data1->{duration}
);
... then of course all that data is going to be on one line.
Upvotes: 0
Reputation: 25
i figured it out...i just used:
my $content=$spectrum->{'content'};
$content=~s/\s+$//g
and that did the trick
Upvotes: 0
Reputation: 161
Just put how many character you want in the printf: e.g.
printf FILE ("%20s %20s %40s %10s\n",...)
Upvotes: 1