问题描述
我需要在Perl程序中处理一些HTTP URL,但是我怀疑 URI
班上帮我.
I need to handle some HTTP URLs in a Perl program, but I have doubts how should the URI
class help me.
尤其是,我希望使用URI
类来解析相对URL并获取其组件.但是,问题是:
Particularly, I'd like the to use the URI
class for resolving relative URLs and getting their components. However, the problems are:
-
我需要一个函数来同时使用
URI
对象和URI字符串作为参数(或确保仅传递一个)
I need a function to work with both
URI
objects and URI strings as arguments (or ensure only one gets passed)
sub foo_string_or_url {
my $uri = URI->new(shift);
这是正确的方法吗?我不太喜欢它,因为它会对URI
进行字符串化并不必要地创建新对象.
is that the right approach? I don't quite like it, because it stringifies the URI
and creates new object unnecessarily.
提取成分
my $host = $uri->host;
这也是有问题的,因为并非所有URI
都具有宿主,特别是如果有人将垃圾传递给该函数,则会die()
.
This is also problematic, because not all URI
s have host, particularly, if someone passes garbage to the function, this will die()
.
解析相对网址
my $new_url = URI::URL->new($uri, $base)->abs;
IIUC,如果没有->abs
,结果仍将字符串化为相对URL(并且不适用于HTTP::Request
),对吗?另外,是否可以保证返回URI
?
IIUC, without the ->abs
, the result will still stringify to the relative URL (and will not work for HTTP::Request
s), am I right? Also, is this guaranteed to return a URI
?
我应该如何处理这些问题?可能性是
How should I handle these problems? The possibilities are
- 始终使用
->isa('URI')
和->can("host")
- 我似乎容易犯错误并且很丑
- 我还是宁愿使用库解决方案,也不愿调试自己的库
- 看到第一点
使用
URI
类是否有理智,防呆的方法?我没有想到过的简单事情(在上面的列表中)?Is there a sane, fool-proof way of using the
URI
classes? Something simple I haven't thought of (in the list above)?推荐答案
我认为可以总结一下您的问题:参数验证是乏味的,我该怎么办?
I think your question can be summarised: parameter validation is tedious, what do I do about it?
-
我也不喜欢.这是开发人员之间意见分歧的问题,其他人说,强制"比切成薄片的面包要好,尤其是当由Moose自动完成时.我认为只允许一种简化程序.同样,YAGNI适用于绝大多数情况.拒绝错误的类型,使用帮助器模块,例如 Params :: Validate / MooseX :: Method :: Signatures / MooseX :: Declare 以避免手动检查显示在您的代码示例中.
I don't like it, either. This is a matter of differing opinion among developers, other say coercions are better than sliced bread, especially when automatically done by Moose. I argue that allowing only one type of simplifies the program. Also, YAGNI applies in the vast majority of cases. Reject wrong types, employ a helper module such as Params::Validate/MooseX::Method::Signatures/MooseX::Declare in order to avoid the manual checks as shown in your code samples.
这是所需的行为.异常处理机制使您可以编写适合每种情况的自定义代码.如果您认为它在美学上不令人满意,请将其删除,并注意使异常不受检查的后果.
This is the desired behaviour. Exception handling mechanisms let you write custom code appropriate for each situation. If you think it's not aesthetically pleasing, remove it and mind the consequences of letting exceptions go unchecked.
use Try::Tiny; my $host; try { $host = $uri->host; } catch { warn "Could not determine host for $uri. Message was: $_. Retry/abort/ignore?\n"; … };
-
是,是.
Yes and yes.
这篇关于我应该如何使用Perl URI类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!