2

Question: I would like to print the output into CSV file instead of in the command prompt itself.

Here is the piece of code in 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";  
}

Output in command prompt

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

Required Output in CSV file

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

1 Answer 1

2

Store the input values in an array and then print them to a file.

#!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";
Sign up to request clarification or add additional context in comments.

10 Comments

I am getting an error Unknown PerlIO layer "outfile" at htmlparse.pl line 22. Unable to open <outfile> for writing : No such file or directory at htmlparse.pl line 22.. Here the line 22 is open(my $OUTFILE, "<outfile>", "rw")
@arka.b You have to replace "<outfile>" with the real file name.
I am using now as this open(my $OUTFILE, "test.csv", "rw") and I am getting this error Unknown open() mode 'test' at htmlparse.pl line 22.
Have changed my answer to open(my $OUTFILE, ">", "<outfile>" ). Try again.
It is working, but the entire output in two boxes. How about using comma (,) in the excel output ConnectionTime,signalstrength,ulCurrentDataRate, batterystatus and then in the next line 03:20:59:46,Good,2.48 Kbps,Fully Charged
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.