Search code examples
perlmojolicious

How to add multiple paths in Perl's Mojo::URL?


How can I add multiple path's to a Mojo::URL object? Consider the example below:

perl -Mojo -E 'say new Mojo::URL("https://httpbin.org/")->path("bytes")->path($_)->to_abs for (1..3)'

Desired output:

https://httpbin.org/bytes/1
https://httpbin.org/bytes/2
https://httpbin.org/bytes/3

Actual output:

https://httpbin.org/1
https://httpbin.org/2
https://httpbin.org/3

Doing ->path("bytes/$_") seems wrong.


Solution

  • Your example almost works, but the problem is that

    Mojo::URL->new("https://httpbin.org/")->path("bytes")
    

    constructs the URL https://httpbin.org/bytes, which has a "base" of https://httpbin.org/. When you do ->path("1") on it, that's resolved relative to the base, which means that 1 replaces bytes.

    Instead if you do

    Mojo::URL->new("https://httpbin.org/")->path("bytes/")->path("$_")
    

    with an added /, you get exactly the result you wanted.

    This is because something that's constructing an HTTP URL doesn't know what's a "directory" and what isn't unless the URL makes it clear with a slash. That's why webservers traditionally redirect you to a URL ending in a slash if you access a directory's path without the trailing slash.