Perl Excel – 无法在未定义的值上调用方法值。当文本是另一个单元格的子string时删除单元格

我有以下parsingExcel文件的代码。对于每一行,如果一个单元格是同一行另一个单元格的子string,我想要删除这个单元格。

我的数据(在.xls文件中)如下所示:

Number1 Text1 Text2 Text3 ... TextN Number2 Number3 ... NumberN 

每个数字和每个文本都在不同的单元格中。 每行的数字和文本的数量可能会有所不同..我想检查如果Text1是Text2Text3的子string等…如果Text3Text4 Text5的子string等..如果他们是子string,我想删除这些细胞。

 #!/usr/bin/perl -w use strict; use warnings; use Spreadsheet::ParseExcel; use diagnostics; my $parser = Spreadsheet::ParseExcel->new(); my $workbook = $parser->parse('test.xls'); if ( !defined $workbook ) { die $parser->error(), ".\n"; } for my $worksheet ( $workbook->worksheets() ) { my ( $row_min, $row_max ) = $worksheet->row_range(); my ( $col_min, $col_max ) = $worksheet->col_range(); for my $row ( $row_min .. $row_max ) { for my $col ( $col_min .. $col_max ) { my $cell = $worksheet->get_cell( $row, $col ); my $test = $cell->value(); if (defined $test) { my $cellValue = $cell->value(); print"The cell value is $cellValue \n"; } else { print "Cell value is not defined \n"; } #my $nextCell = $worksheet->get_cell( $row, $col+1 ); #if (index($nextCell->value(), $cell->value()) != -1) { #print "$nextCell->value() contains $cell->value()\n"; #} #next unless $cell; } } } 

我得到一个错误Can't call method "value" on an undefined value at ...我相信这是与事实,当行中的最后一个单元格被发现, $cell->value函数失败,因为单元格是空的..我试着检查,如果值是未定义的,所以我避免处理这个单元格,但我仍然得到相同的错误.. Perl如何处理空单元格? 我怎样才能避免得到这个错误? 谢谢 !

错误的意思是$cell在你调用$cell->value时候是undef。

如果你只是想跳过空单元格,为什么不添加

 next unless $cell; 

在你for my $col ( ... )循环中

编辑:

你可以添加

 if( my $test = $cell->value() ){ $cell->delete if grep{ ( my $forward = $worksheet->get_cell( $row, $_ ) ) && ( $forward =~ /\Q$test\E/ } ( $col+1 .. $colMax ); } 

编辑:这不起作用(我不知道,不能在当时testing)。 抱歉。

或者首先声明一个临时variables$ forward,AND(这也是错误的)call – > value:

 if( my $test = $cell->value() ){ my $forward; $cell->delete if grep{ ( $forward = $worksheet->get_cell( $row, $_ )->value ) && ( $forward =~ /\Q$test\E/ } ( $col+1 .. $colMax ); } 

或者,也许更好,把它写成一个for循环(我试图让自己太聪明)

 for my $pos ( $col+1 .. $colMax ){ my $forward_cell = $worksheet->get_cell( $row, $pos ); if ( $forward_cell->value =~ /\Q$text/ ){ $cell->delete; last; } } 

这优雅地回到了我以前的观点:这看起来效率低下

但是,首先获取所有实际存在的单元格然后删除,可能会更有效率,然后再次查找匹配文本的后续单元格。 不知道你想要做什么/\Q$text\E//^\Q$text\E/ (string以$ text开始),并且你可能不需要\Q ... \E因为它只能转义特殊字符如果没有的话是不必要的。