Search code examples
perluricpan

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

Another example

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

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

This clearly a bug right? But no one seems to be bothered at all! No one reported this bug in https://rt.cpan.org/Public/Dist/Display.html?Name=URI. I tried to report one but getting bitcard account sucks.

What are you using in your case? Simple regex?

What I am using?

  • Perl version: v5.10.1
  • URI version : 1.37

Solution

  • URI is fine.

    This is a very good example for why you should always use strict and use 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
    

    Now with 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.
    

    And now with use warnings on top.

    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.
    

    It's pretty clear what is wrong here. Perl thinks @host is a variable because you have it in double quotes "".

    Possible unintended interpolation of @host in string

    Either escape it using "user\@host" or use single quotes '' like 'user@host'.