使用Perl,如何在网络上解码或创建这些%编码? [英] Using Perl, how do I decode or create those %-encodings on the web?

查看:74
本文介绍了使用Perl,如何在网络上解码或创建这些%编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的Perl脚本中处理URI(即百分比)编码和解码.我该怎么办?

I need to handle URI (i.e. percent) encoding and decoding in my Perl script. How do I do that?

这是来自官方代表的问题.我们正在导入perlfaq到Stack Overflow .

This is a question from the official perlfaq. We're importing the perlfaq to Stack Overflow.

推荐答案

这是官方常见问题解答减去后续修改.

这些%编码处理URI中的保留字符,如 RFC 2396第2节.这种编码将保留的字符替换为US-ASCII表中字符编号的十六进制表示形式.例如,冒号:变为%3A.

Those % encodings handle reserved characters in URIs, as described in RFC 2396, Section 2. This encoding replaces the reserved character with the hexadecimal representation of the character's number from the US-ASCII table. For instance, a colon, :, becomes %3A.

在CGI脚本中,如果您使用的是 CGI.pm <,则不必担心解码URI. /a>.您不必在进入或退出过程中都自己处理URI.

In CGI scripts, you don't have to worry about decoding URIs if you are using CGI.pm. You shouldn't have to process the URI yourself, either on the way in or the way out.

如果必须自己对字符串进行编码,请记住,切勿尝试对已经组成的URI进行编码.您需要分别转义组件,然后将它们放在一起.要对字符串进行编码,可以使用 URI :: Escape 模块. uri_escape函数返回转义的字符串:

If you have to encode a string yourself, remember that you should never try to encode an already-composed URI. You need to escape the components separately then put them together. To encode a string, you can use the URI::Escape module. The uri_escape function returns the escaped string:

my $original = "Colon : Hash # Percent %";

my $escaped = uri_escape( $original );

print "$escaped\n"; # 'Colon%20%3A%20Hash%20%23%20Percent%20%25'

要解码字符串,请使用uri_unescape函数:

To decode the string, use the uri_unescape function:

my $unescaped = uri_unescape( $escaped );

print $unescaped; # back to original

如果您想自己做,只需要将保留的字符替换为其编码.全局替换是实现此目的的一种方法:

If you wanted to do it yourself, you simply need to replace the reserved characters with their encodings. A global substitution is one way to do it:

# encode
$string =~ s/([^^A-Za-z0-9\-_.!~*'()])/ sprintf "%%%0x", ord $1 /eg;

#decode
$string =~ s/%([A-Fa-f\d]{2})/chr hex $1/eg;

这篇关于使用Perl,如何在网络上解码或创建这些%编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆