Given a $path_spec (described below) and a
$path, this will either bind the path to the spec
and return and array of bound values, or it will return nothing. Returning
nothing indicates that no match was found. Additionally, if this function
is called in scalar context, and there is only one match, it will return
that item. Otherwise it will return the array as normal. This all makes it
easy to use the following idiom:
if ( my $id = bind_path( '/:id', $request->path_info ) ) {
# handle the case with an ID here
}
else {
# handle other cases here
}
The $path_spec follows a pretty
standard convention. Literal path parts must match corresponding
literal. Variable path parts are prefixed by a colon and are captured
for returning later, if a question mark (?) prefixes the colon, that
element will be considered optional. And lastly the "splat"
operator ("*") is supported and causes
all the rest of the path segments to be returned. Below are a few
examples of this:
spec path result
------------------------------------------------------------
/test/:foo/:bar /test/1/2 ( 1, 2 )
/test/:foo/:bar /test/1/ undef #failure-case
/test/* /test/1/2/3 ( 1, 2, 3 )
/user/:id/:action /user/1/edit ( 1, 'edit' )
/?:id /201 ( 201 )
/?:id / ( )
This function is kept deliberately simple and it is expected
that the user will use "my" in the
array form to assign multiple variables, like this:
my ( $foo, $bar ) = bind_path( '/test/:foo/:bar', $path );
In the future we might add a
"bind_path_hash" function which
captures the variable names as well, but to be honest, if you feel you
need that, you likely want one of the many excellent path dispatching
modules available on CPAN.
NOTE: Some care should be taken when using path specs
in which the only things are either optional parameters (prefixed with
"?:") or the "splat"
operator ("*") as they can return
empty arrays, which in certain contexts can look like match failure. In
these cases you can test the match in scalar context to verify, a match
failure will be "undef" whereas a
match success (in which nothing was matched) will return
0 (indicating an array with zero size).