I'm iterating through a list of links on a page, creating a URI object for each. When the URI object is created, I don't know whether the URL has a scheme, so when I later call $uri->host()
, I will sometimes get
Can't locate object method "host" via package "URI::_generic" at -e line 1.
because the URI object is of type URI::_generic
, and doesn't have a host() attribute.
I could check before object creation with regex, or I could wrap the $uri->host()
call in an eval
block to handle the exception, but I figure there has to be a more suave method than either of those.
My suggestion: use the built in language features to your advantage before a regex.
Instead of a regex, you can do this:
if ($uri->can('host')) {
say "We're good!";
}
...to see if it's available. You could also check it's type:
if ($uri->isa('URI::_generic')) {
die 'A generic type - not good!' ;
}
...and verify that you have one that's good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With