Author image Daisuke Maki
and 1 contributors


URI::Match - Match URLs By Parts


  use URI;
  use URI::Match;

  my $uri = URI->new("");

  # Match just a single part of the URL
  if ( $uri->match_parts( host => qr/^(?!www).+\.cpan\.org$/ )) {
    # matched

  # Match using a subroutine
  my $code = sub {
    my ($host, $url) = @_;
    return $host eq '';
  if ( $uri->match_parts( host => $code ) ) {
    # matched

  # Match using an object
  my $object = My::Matcher->new(); # must implement "match"
  if ( $uri->match_parts( host => $object ) ) {
    # matched

  # Match several parts
  my $code = sub {
    my ($path, $url) = @_;
    return $path ne '/';
  if ( $uri->match_parts(
        host => qr/^(?!www).+\.cpan\.org$/,
        path => $code
  )) {
    # matched

  # Match the whole URL (just for completeness) 
  if ($uri->match_parts( qr{^http://search\.cpan\.org} )) {
    # matched


This is a simple utility that adds ability to match URL parts against regular expressions, subroutines, or objects that implement a match() method.

Since this module uses loops and method calls, writing up a clever regular expression and using it directly against the whole URL is probably faster. This module aims to solve the problem where readability matters, or when you need to assemble the match conditions at run time.

URI::Match adds the following methods to the URI namespace.



Matches the URI object against the given conditions. The conditions can be given as a single scalar or a hash. If given a single scalar, it will match against the whole URI. Otherwise, the key value will be taken as the part to match the condition against.

For example,

  $uri->match_parts( qr{^$} )

Will only match if the entire URL matches the regular expression above. But If you want to match against several different schemes (say, http and ftp) and aother set of hosts, you could say:

    scheme => qr{^(?:ftp|http)$},
    host   => qr{^.+\.example\.com$}

Conditions can be either a scalar, a regular expression, a subroutine, or an object which implements a match() method. Simple scalars are treated as regular expressions.


Copyright (c) 2007 Daisuke Maki <>


This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.