Perl输出到CSV文件

时间:2015-07-21 05:57:45

标签: perl csv automation

问题: 我想打印输出到CSV文件而不是在命令提示符本身。

以下是perl中的一段代码:

#!/usr/bin/perl

use strict;
use warnings;
use HTML::TokeParser::Simple;

my $url = '<some URL>';
my $parser = HTML::TokeParser::Simple->new( url => $url );
my %tags;
while ( my $tag = $parser->get_tag('input') ) {
    my $id    = $tag->get_attr('id');    # get id attribute value    
    my $value = $tag->get_attr('value'); # get value attribute value
    $tags{$id} = $value;
}

for (keys %tags) {
    print "$_ => $tags{$_} \n";  
}

在命令提示符下输出

ConnectionTime => 03:20:59:46
signalstrength => Good
ulCurrentDataRate => 2.48 Kbps
batterystatus => Fully Charged

CSV文件中的必需输出

ConnectionTime signalstrength ulCurrentDataRate batterystatus
03:20:59:46 Good 2.48 Kbps Fully Charged

1 个答案:

答案 0 :(得分:2)

将输入值存储在数组中,然后将它们打印到文件中。

#!usr/bin/perl

use strict;
use warnings;
use HTML::TokeParser::Simple;

my $url = '<some URL>';
my $parser = HTML::TokeParser::Simple->new(url => $url);
my %tags;
while (my $tag = $parser->get_tag('input')) {
           my $id=$tag->get_attr('id'); # get id attribute value    
           my $value = $tag->get_attr('value'); # get value attribute value
           $tags{$id}=$value;
 }
my @tags;
my @values;
for (keys %tags){
   push (@tags, $_);
   push (@values, $tags{$_});
}

open(my $OUTFILE, ">", "<outfile>" )
    or die "Unable to open <outfile> for writing : $!";
print $OUTFILE join("\t",@tags)."\n";
print $OUTFILE join("\t",@values)."\n";