我正在使用 HTML::TreeBuilder 解析房地产网页,并具有以下代码:
$values{"Pcity"} = $address->look_down("_tag" => "span",
"itemprop" => "addressLocality")->as_text;
$values{"PState"} = $address->look_down("_tag" => "span",
"itemprop" => "addressRegion")->as_text;
某些页面不包含城市或州,解析器退出并出现错误:
Can't call method "as_text" on an undefined value
为了修复它,我使用了以下方法:
$values{"Pcity"} = $address->look_down("_tag" => "span",
"itemprop" => "addressLocality");
if(defined($values{"Pcity"}))
{
$values{"Pcity"} = $values{"Pcity"}->as_text;
}
else
{
$values{"Pcity"} = '';
}
它可以工作,但现在我有 9 行而不是 1 行。由于我有很多这样的地方,代码会变得相当大。
有什么办法可以优化吗?