perloptimizationhtml-parsinghtml-tree

HTML::Tree: Can't call method "as_text" on an undefined value


I am parsing a real estate web page, using HTML::TreeBuilder, and have the following code:

$values{"Pcity"} = $address->look_down("_tag" => "span", 
                   "itemprop" => "addressLocality")->as_text;
$values{"PState"} = $address->look_down("_tag" => "span", 
                   "itemprop" => "addressRegion")->as_text;

Some pages don't contain city or state, and the parser exits with an error:

Can't call method "as_text" on an undefined value

To fix it I used the following method:

$values{"Pcity"} = $address->look_down("_tag" => "span", 
                   "itemprop" => "addressLocality");
if(defined($values{"Pcity"}))
{
    $values{"Pcity"} = $values{"Pcity"}->as_text;
}
else
{
    $values{"Pcity"} = '';
}

It works, but now instead of 1 line I have 9. And as I have many places like this the code will become considerably bigger.

Is there any way to optimize?


Solution

  • This is shorter:

    $a = $address->look_down("_tag" => "span", "itemprop" => "addressLocality");
    $values{"Pcity"} = $a ? $a->as_text : '';