如何检查是否可以在 Perl 中对 URI 对象调用 host() ?
我正在迭代页面上的链接列表,为每个链接创建一个 URI 对象。当创建URI对象时,我不知道该URL是否有scheme,所以当我稍后调用$uri->host()
时,有时会得到
Can't通过包“URI::_generic”在 -e 第 1 行找到对象方法“host”。
因为 URI 对象的类型为 URI::_generic
,并且没有主机() 属性。
我可以在使用正则表达式创建对象之前进行检查,或者可以将 $uri->host()
调用包装在 eval
块中来处理异常,但我认为有必须是比这两种方法更温和的方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的建议:在正则表达式之前使用内置的语言功能来发挥您的优势。
您可以执行以下操作,而不是使用正则表达式:
...查看它是否可用。您还可以检查它的类型:
...并验证您是否拥有一个好的类型。
My suggestion: use the built in language features to your advantage before a regex.
Instead of a regex, you can do this:
...to see if it's available. You could also check it's type:
...and verify that you have one that's good.
UNIVERSAL 类(perldoc UNIVERSAL)确实非常有用;它包含:
$obj->can( METHOD )
,用于确定 METHOD 在 $obj 类上是否可用(或者您可以使用裸类名而不是受祝福的对象 - 用于鸭子打字!$obj->isa( TYPE )
,用于确定 $obj 是否是 TYPE 类型或者是 TYPE 的后代(本质上,检查 ref($obj) 是否为在 TYPE 的 @ISA 数组中)(也允许裸类名) - 用于一些多态实现VERSION
,用于获取模块的版本字符串( boorrrrring)The UNIVERSAL class (perldoc UNIVERSAL) is pretty useful indeed; it contains:
$obj->can( METHOD )
, for determining if METHOD is available on the $obj class (or you can use a bare classname rather than a blessed object - used for duck typing!$obj->isa( TYPE )
, for determining if $obj is type TYPE or is descended from TYPE (essentially, checks if ref($obj) is in TYPE's @ISA array) (bare classname also allowed) - used for some polymorphic implementationsVERSION
, for getting a module's version string (boorrrrring)