How can I check if I can call host () on a URI object in Perl?

I repeat the list of links on the page, creating a URI for each. When the URI object is created, I don't know if the URL has a scheme, so when I call later $uri->host(), I sometimes get

Can't locate object method "host" via package "URI::_generic" at -e line 1.

because the URI is of type URI::_genericand does not have the host () attribute.

I could check before creating the object with a regular expression, or I could wrap the call $uri->host()in a block evalto handle the exception, but I believe that there should be a safer method than any of them.

+5
source share
2 answers

: .

:

if ($uri->can('host')) {
    say "We're good!";
}

... , . :

if ($uri->isa('URI::_generic')) {
    die 'A generic type - not good!' ;
}

... , - .

+13

UNIVERSAL (perldoc UNIVERSAL) ; :

  • $obj->can( METHOD ), , METHOD $obj ( , , duck typing

  • $obj->isa( TYPE ), , $obj TYPE TYPE ( , , ref ($ obj) TYPE @ISA) ( ) -

  • VERSION, (boorrrrring)

+4

All Articles