【问题标题】:Perl output into CSV filePerl 输出到 CSV 文件
【发布时间】:2015-07-21 15:24:08
【问题描述】:

问题: 我想将输出 print 到 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

【问题讨论】:

    标签: perl csv automation


    【解决方案1】:

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

    #!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";
    

    【讨论】:

    • 我收到一个错误Unknown PerlIO layer "outfile" at htmlparse.pl line 22. Unable to open &lt;outfile&gt; for writing : No such file or directory at htmlparse.pl line 22.。这里第 22 行是 open(my $OUTFILE, "", "rw")
    • @arka.b 您必须将“”替换为真实文件名。
    • 我现在使用这个open(my $OUTFILE, "test.csv", "rw"),我在htmlparse.pl第22行收到这​​个错误Unknown open() mode 'test'。
    • 已将我的答案更改为open(my $OUTFILE, "&gt;", "&lt;outfile&gt;" )。再试一次。
    • 它正在工作,但整个输出在两个框中。如何使用逗号 (,) 在 excel 输出中 ConnectionTime,signalstrength,ulCurrentDataRate, batterystatus 然后在下一行 03:20:59:46,Good,2.48 Kbps,Fully Charged
    猜你喜欢
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多