Balakumar
Balakumar

Reputation: 650

Skip the method dom->find() if its fails

I am using Mojo::DOM for parsing HTML content.The issue i am facing is the program terminate if the function dom->find() fails,Its showing a error cannot locate object error . how can i skip the error and continue the execution of the program. Please give me some suggestions.

Upvotes: 1

Views: 72

Answers (2)

rjh
rjh

Reputation: 50304

If you know $dom is an object but don't know if it has the method you want, use can:

if($dom->can('find')) {
    # do something with $dom->find('arg');
}

This approach is useful for modules like URI which return different subclasses (with different methods) depending on the constructor arguments.

Upvotes: 0

Gilles Quénot
Gilles Quénot

Reputation: 185530

The basic way to do this is :

eval{ $dom->find('arg'); };
warn "eval had returned this error : [$@]\n" if $@;

Or with Try::Tiny :

try {
    $dom->find('arg');
} catch {
    warn "caught error: $_"; # not $@
};

Upvotes: 2

Related Questions