1

Possible Duplicate:
Extract Table Contents using Perl

I am trying to extract table content from a html file using HTML::TableExtract. My problem is my html file is structured in the following way:


!DOCTYPE html>
<html>
<body>

    <h4>One row and three columns:</h4>

    <table border="1">
      <tr>
        <td>
        <p> 100 </p></td>
        <td>
        <p> 200 </p></td>
        <td>
        <p> 300 </p></td>
        </tr>
      <tr>
        <td>
        <p> 100 </p></td>
        <td>
        <p> 200 </p></td>
        <td>
        <p> 300 </p></td>
        </tr>
    </table>
</body>

Because of this structure, my output looks like:


   100|

   200|

   300|

   400|

   500|

   600|

Instead of what I want:

   100|200|300|
   400|500|600|

Can you please help? Here is my perl code

use strict;
use warnings;
use HTML::TableExtract;

my $te = HTML::TableExtract->new();
$te->parse_file('Table_One.html');

open (DATA2, ">TableOutput.txt")
    or die "Can't open file";

foreach my $ts ($te->tables()) {

    foreach my $row ($ts->rows()) {

        my $Final = join('|', @$row );
    print DATA2 "$Final";
    }
}
close (DATA2);
4

1 回答 1

1
sub trim(_) { my ($s) = @_; $s =~ s/^\s+//; $s =~ s/\s+\z//; $s }

foreach my $ts ($te->tables()) {
    foreach my $row ($ts->rows()) {
        print DATA2 join('|', map trim, @$row), "\n";
    }                                            
}                                                 ^
                                                  |
                                                  |

Or if you really want the trailing "|",

sub trim(_) { my ($s) = @_; $s =~ s/^\s+//; $s =~ s/\s+\z//; $s }

foreach my $ts ($te->tables()) {
    foreach my $row ($ts->rows()) {
        print DATA2 (map { trim($_).'|' } @$row), "\n";
    }
}
于 2012-10-23T19:40:38.940 回答