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

Sam*_*ron 0 perl uri cpan

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
Run Code Online (Sandbox Code Playgroud)

另一个例子

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

output>>>
ssh://username/path/to/file.txt
Run Code Online (Sandbox Code Playgroud)

这显然是一个错误吗?但似乎没有人感到困扰!在https://rt.cpan.org/Public/Dist/Display.html?Name=URI中没有人报告此错误.我试图报告一个,但让bitcard帐户很糟糕.

在你的情况下你在用什么?简单的正则表达式?

我在用什么?

  • Perl版本:v5.10.1
  • URI版本:1.37

Sob*_*que 9

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

在字符串中可能无意中插入了@host

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

ssh://username/path/to/file.txt
Run Code Online (Sandbox Code Playgroud)

这不是你认为你发送的.

#!/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";
Run Code Online (Sandbox Code Playgroud)

但是,确实给出了所需的输出.

注意 - 我改变了new行,因为new URI是间接对象表示法,并且URI->new是更好的样式.


sim*_*que 6

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
Run Code Online (Sandbox Code Playgroud)

现在用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.
Run Code Online (Sandbox Code Playgroud)

而现在有了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.
Run Code Online (Sandbox Code Playgroud)

很清楚这里有什么问题.Perl认为@host是一个变量,因为你有双引号"".

在字符串中可能无意中插入了@host

或者使用转义"user\@host"或用单引号''一样'user@host'.