in reply to Re: Splitting an url in its components
in thread Splitting an url in its components

Wow, that's pretty freaking elegant.
I like this example more than the one after, because it's legible.
Nice YAML touch- Thank you for showing us!
  • Comment on Re^2: Splitting an url in its components

Replies are listed 'Best First'.
Re^3: Splitting an url in its components
by massa (Hermit) on Jul 17, 2008 at 22:14 UTC
    At your service... :-)
    I like the first example better, too, but the second one gets more parts of the URI separated... and that's why I had to break it in so many lines! As for YAML, it's my favourite debugging tool (I think it's far more legible than Data::Dump(er)?)
    []s, HTH, Massa
      Its better if you use the official regex :)
      From the URI documentation:

      As an alternative to this module, the following (official) regular expression can be used to decode a URI:

      my($scheme, $authority, $path, $query, $fragment) = $uri =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:# +(.*))?|;
        The POD for URI does not explain why this regex is "official"; in any case, it does not match correctly mailto: URIs. But my regexes did not count fragments, so they were not quite right either. New version follows:
        sub url_segments { local($_) = @_; my $uri_re = qr{ (?: ([a-z]{3,6}) # proto : (?: // )? )? ( # authority (?: ([a-z0-9_-]+) # user (?: : ([^@]+) )? @ # password )? ( [a-z0-9._-]+ ) # domain (?: : (\d+) )? # port ) (?: ( # path ( .*? / ) # location ( # filename ( [^?#/]*? ) # filename_only ( (?: \. \w*[a-z]\w* )* ) # ext ) ) (?: \? ( [^#]* ) )? # query (?: \# ( .* ) )? # fragment )? }xi; my @matches = /\A($uri_re)\Z/; return unless @matches; my $segments; my @parts = qw(uri proto authority user pass domain port path location filename filename_only ext query frag); $matches[$_] and push @$segments, { $parts[$_] => $matches[$_] } for 0 .. $#parts; $segments }
        Works quite reliably in preliminary tests :-)
        Update: oops, a "?" was missing in the password line. fixed.
        []s, HTH, Massa