本文介绍了我应该如何使用Perl URI类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在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:

  1. 我需要一个函数来同时使用URI对象和URI字符串作为参数(或确保仅传递一个)

  1. 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 URIs 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::Requests), am I right? Also, is this guaranteed to return a URI?

我应该如何处理这些问题?可能性是

How should I handle these problems? The possibilities are

08-01 02:19