Saturday, July 16, 2011

Autoincrement an html table serial numbers using Perl script

This perl script will append a new column along with the table with each row serial number incrementing from 1.

Input: 1) A file containing single table. This should not be further nested one and also should not contain colspan or rowspan

Script:

#!/usr/bin/perl -w

#This assumes

# any html file containing tables which may have tbody. This code only adds single column and does not change anything else.

use strict;

use feature "switch";

use Common;

use HTML::Element;

use HTML::TreeBuilder;

my $filename="F:/tmp/t1.html";

my $toc;

sub autoincrement

{

my $table=$_[0];



#see if tboday is present

my @children=$table->content_list();



foreach my $item (@children)

{

if($item->tag() eq "tbody")

{

$table = $item;

last;

}



}







my @rows = grep { $_->tag() eq "tr" } $table->content_list();



#First row is header row

my HTML::Element $th = HTML::Element->new('th');

$th->push_content("SNo.");

$rows[0]->unshift_content($th);



for(my $i=1;$i<@rows;++$i)

{

my HTML::Element $td = HTML::Element->new('td');

$td->push_content($i);

$rows[$i]->unshift_content($td);



}







}

die "File $filename not found" if !-r $filename;

my $tree = HTML::TreeBuilder->new();



$tree->parse_file($filename);





my @h = $tree->content_list();





my @all_elements=$h[1]->content_list();



foreach my $item (@all_elements)

{



autoincrement($item) if ref(\$item) ne "SCALAR" and $item->tag() eq "table";



}





my @list1=$tree->content_list();



my @list2=$list1[1]->content_list();



foreach my $table (@list2)

{

print $table->as_HTML();

}



# Finally:

 

No comments:

Post a Comment