10 use overload '""' => \&as_string;
14 URI::Template - Object for handling URI templates
19 my $template = URI::Template->new( 'http://example.com/{x}' );
20 my $uri = $template->process( x => 'y' );
21 # uri is a URI object with value 'http://example.com/y'
23 my %result = $template->deparse( $uri );
24 # %result is ( x => 'y' )
28 This is an initial attempt to provide a wrapper around URI templates
29 as described at http://www.ietf.org/internet-drafts/draft-gregorio-uritemplate-00.txt
33 To install this module via Module::Build:
36 ./Build # or `perl Build`
37 ./Build test # or `perl Build test`
38 ./Build install # or `perl Build install`
40 To install this module via ExtUtils::MakeMaker:
49 =head2 new( $template )
51 Creates a new L<URI::Template> instance with the template passed in
52 as the first parameter.
58 my $templ = shift || die 'No template provided';
59 my $self = bless { template => $templ }, $class;
66 Returns the original template string. Also used when the object is
72 return $_[ 0 ]->{ template };
77 Returns an array of variable names found in the template. NB: they
78 are returned in random order.
84 my %vars = map { $_ => 1 } $self->as_string =~ /{(.+?)}/g;
88 =head2 process( %vars )
90 Given a list of key-value pairs, it will URI escape the values and
91 substitute them in to the template. Returns a URI object.
97 return URI->new( $self->process_to_string( @_ ) );
100 =head2 process_to_string( %vars )
102 Processes key-values pairs like the C<process> method, but doesn't
103 inflate the result to a URI object.
107 sub process_to_string {
109 my @vars = $self->variables;
111 my $uri = $self->as_string;
114 for my $var ( @vars ) {
115 $params{ $var } = '' unless defined $params{ $var };
118 my $regex = '\{(' . join( '|', map quotemeta, @vars ) . ')\}';
119 $uri =~ s/$regex/URI::Escape::uri_escape($params{$1})/eg;
124 =head2 deparse( $uri )
126 Does some rudimentary deparsing of a uri based on the current template.
127 Returns a hash with the extracted values.
135 if( !$self->{ deparse_re } ) {
136 my $templ = $self->as_string;
137 $self->{ vars_list } = [ $templ =~ /{(.+?)}/g ];
138 $templ =~ s/{.+?}/(.+?)/g;
139 $self->{ deparse_re } = qr/$templ/;
142 my @matches = $uri =~ $self->{ deparse_re };
145 @results{ @{ $self->{ vars_list } } } = @matches;
153 =item * Brian Cassidy E<lt>bricas@cpan.orgE<gt>
157 =head1 COPYRIGHT AND LICENSE
159 Copyright 2007 by Brian Cassidy
161 This library is free software; you can redistribute it and/or modify
162 it under the same terms as Perl itself.