Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

uri

perl

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.

like image 792
Drew Stephens Avatar asked Sep 29 '09 21:09

Drew Stephens


1 Answers

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.

like image 66
Robert P Avatar answered Sep 28 '22 00:09

Robert P