所以我在perl中有这个代码解析xml,我希望perl文件打印到文本文件中,这样所有内容都在列中,如下所示:
SpectrumIndex TotalIonCount Duration Spectrum
Integer Float Float mass,abundance;mass1,abundance1;mass 2,abundance1
这是xml代码:
<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>
但是使用以下perl代码:
#!/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});
}
}
它将以下输出提供给文本文件:
SpectrumIndex TotalIonCount Spectrum Duration
Integer Float mass,abundance;mass1,abundance1;
mass2,abundance2;mass6,abundance6 Float
Integer Float mass3,abundance3;mass4,abundance4;
mass5,abundance5 Float
感谢任何帮助!
答案 0 :(得分:1)
只需在printf中输入您想要的字符数: e.g。
printf FILE ("%20s %20s %40s %10s\n",...)
答案 1 :(得分:0)
在现代的perl中:
open my $INFILE, '<', $fname
or die "Couldn't open $fname: $!";
您必须逐行打印。您不能打印一列,然后打印另一列 所以当你这样做时:
printf FILE (
"%-s %-s %-s %-s\n",
$data->{"spectrum-index"},
$data->{tic},
$spectrum->{'content'},
$data1->{duration}
);
...当然所有数据都将在一行上。
答案 2 :(得分:0)
我想通了......我刚才用过:
my $content=$spectrum->{'content'};
$content=~s/\s+$//g
这就是诀窍