Perl URI class 错误地解析用户信息 | perl 中严格和警告的重要性

Perl URI class wrongly parse user info | Importance of strict and warnings in perl

use URI;
my $url = new URI("ssh://username@host/path/to/file.txt");
print "User: ", $url->user, "\n";
print "Host: ", $url->host, "\n";
print "Path: ", $url->path, "\n";

output>>>
    User:
    Host: username
    Path: /path/to/file.txt

 expected output>>>
    User: username
    Host: host
    Path: /path/to/file.txt

另一个例子

use URI; 
my $url = new URI("ssh://username@host/path/to/file.txt");
print $url->as_string;

output>>>
ssh://username/path/to/file.txt

这显然是一个错误吧?但似乎根本没有人在意! https://rt.cpan.org/Public/Dist/Display.html?Name=URI 中没有人报告此错误。我试图报告一个,但获取 bitcard 帐户很糟糕。

你用的是什么?简单的正则表达式?

我在用什么?

这是一个很好的例子,说明为什么你应该总是 use strict; use warnings;:

Possible unintended interpolation of @host in string

这意味着 - 您实际上并没有发送您认为发送的内容。尝试 printing 它,你会得到:

ssh://username/path/to/file.txt

这不是您认为要发送的内容。

#!/usr/bin/perl

use warnings;
use strict;
use URI;

my $url = URI->new("ssh://username\@host/path/to/file.txt");
print "User: ", $url->user, "\n";
print "Host: ", $url->host, "\n";
print "Path: ", $url->path, "\n";

但是,确实提供了所需的输出。

注意 - 我已经更改了 new 行,因为 new URI 是间接对象表示法,而 URI->new 是更好的样式。

URI 没问题。

这是一个很好的例子,说明了为什么您应该始终 use strictuse warnings

use URI;
my $url = new URI("ssh://username@host/path/to/file.txt");
print $url->user, $url->host, $url->path;

__END__
username/path/to/file.txt

现在 strict

use strict;
use URI;
my $url = new URI("ssh://username@host/path/to/file.txt");
print $url->user, $url->host, $url->path;

__END__
Global symbol "@host" requires explicit package name at /home/simbabque/code/scratch.pl line 1739.
Execution of /home/simbabque/code/scratch.pl aborted due to compilation errors.

现在 use warnings 位于顶部。

use strict;
use warnings;
use URI;
my $url = new URI("ssh://username@host/path/to/file.txt");
print $url->user, $url->host, $url->path;

__END__
Possible unintended interpolation of @host in string at /home/simbabque/code/scratch.pl line 1740.
Global symbol "@host" requires explicit package name at /home/simbabque/code/scratch.pl line 1740.
Execution of /home/simbabque/code/scratch.pl aborted due to compilation errors.

很明显这里出了什么问题。 Perl 认为 @host 是一个变量,因为你把它放在双引号中 "".

Possible unintended interpolation of @host in string

要么使用 "user\@host" 转义它,要么使用单引号 '',例如 'user@host'.