簡體   English   中英

Perl從HTML表打印行和列

[英]Perl printing rows and columns from HTML table

這是我的temp.html

<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

我試圖使用下面的代碼打印上表中的每個元素 -

#!/usr/bin/perl

use strict;
use Data::Dumper;
use HTML::TableExtract;

my $tex = HTML::TableExtract->new(keep_html=>1);

$tex->parse_file('./temp.html');
my ($table) = $tex->tables;
#print Dumper($table);

my $numColumns = @{$table->rows->[0]};
print "\n numColumns = $numColumns\n";
my $numRows = @{$table->rows};
print "\n numRows = $numRows\n";

for my $rowIndex ( 0..$numRows-1 ) { 
    for my $columnIndex ( 0..$numColumns-1 ) { 
       print "\n row $rowIndex column $columnIndex $table->rows->[$rowIndex][$columnIndex] ";
    }   
}

它打印 -

row 0 column 0 HTML::TableExtract::Table=HASH(0x8e7d7f8)->rows->[0][0] 
row 0 column 1 HTML::TableExtract::Table=HASH(0x8e7d7f8)->rows->[0][1] 
row 1 column 0 HTML::TableExtract::Table=HASH(0x8e7d7f8)->rows->[1][0] 
row 1 column 1 HTML::TableExtract::Table=HASH(0x8e7d7f8)->rows->[1][1]

如果我使用@{$table->rows->[$rowIndex]}->[$columnIndex]而不是$table->rows->[$rowIndex][$columnIndex]我得到正確的輸出,但有一個警告。 如何刪除警告?

Using an array as a reference is deprecated at t.pl line 21.

row 0 column 0 row 1, cell 1 
row 0 column 1 row 1, cell 2 
row 1 column 0 row 2, cell 1 
row 1 column 1 row 2, cell 2

你不能在字符串中調用方法。 雖然您可以取消引用字符串中的變量並且也可以從哈希或數組訪問元素,但不支持方法調用。

代替

print "... $table->rows->[$rowIndex][$columnIndex] ";

你要

my $cell_value = $table->rows->[$rowIndex][$columnIndex];
print "... $cell_value ";

其他替代方案包括使用某種解除引用。 你找到了像這樣的解決方案

print "... ${$table->rows->[$rowIndex]}[$columnIndex] ";

這是有效的,因為方法調用現在在一個解除引用的塊中,可以包含任意代碼。 更常見的方法是使用“購物車”偽運算符@{[ ... ]} ,它允許插入任意代碼:

print "... @{[ $table->rows->[$rowIndex][$columnIndex] ]} ";

弄清楚了。

根據https://stackoverflow.com/a/14065917/1729501

@Month_name->[$month] 

應該

$Month_name[$month]

所以在我的情況下,

@{$table->rows->[$rowIndex]}->[$columnIndex]

應該

${$table->rows->[$rowIndex]}[$columnIndex]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM