10 use overload '""' => \&as_string;
12 my $unsafe = q(^A-Za-z0-9\-_.~!\$\&'()*+,;=:/?\[\]#@);
16 URI::Template - Object for handling URI templates
21 my $template = URI::Template->new( 'http://example.com/{x}' );
22 my $uri = $template->process( x => 'y' );
23 # uri is a URI object with value 'http://example.com/y'
25 my %result = $template->deparse( $uri );
26 # %result is ( x => 'y' )
30 This is an initial attempt to provide a wrapper around URI templates
31 as described at http://www.ietf.org/internet-drafts/draft-gregorio-uritemplate-01.txt
42 =head2 new( $template )
44 Creates a new L<URI::Template> instance with the template passed in
45 as the first parameter.
51 my $templ = shift || die 'No template provided';
52 my $self = bless { template => $templ }, $class;
59 Returns the original template string. Also used when the object is
65 return $_[ 0 ]->{ template };
70 Returns an array of unique variable names found in the template.
71 NB: they are returned in random order.
77 my %vars = map { $_ => 1 } $self->all_variables;
81 =head2 all_variables( )
83 Returns an array of variable names found as they appear in template --
84 in order, duplicates included.
90 my @vars = $self->as_string =~ /{(.+?)}/g;
94 =head2 process( %vars|\@values )
96 Given a list of key-value pairs or an array ref of values (for
97 positional substitution), it will URI escape the values and
98 substitute them in to the template. Returns a URI object.
104 return URI->new( $self->process_to_string( @_ ) );
107 =head2 process_to_string( %vars|\@values )
109 Processes input like the C<process> method, but doesn't
110 inflate the result to a URI object.
114 sub process_to_string {
118 return $self->_process_by_position( @_ );
121 return $self->_process_by_key( @_ );
125 sub _process_by_key {
127 my @vars = $self->variables;
129 my $uri = $self->as_string;
132 for my $var ( @vars ) {
134 = defined $params{ $var }
135 ? URI::Escape::uri_escape( $params{ $var }, $unsafe )
139 my $regex = '\{(' . join( '|', map quotemeta, @vars ) . ')\}';
140 $uri =~ s/$regex/$params{$1}/eg;
145 sub _process_by_position {
147 my @params = @{ $_[ 0 ] };
149 my $uri = $self->as_string;
151 $uri =~ s/{(.+?)}/@params
152 ? defined $params[ 0 ]
153 ? URI::Escape::uri_escape( shift @params, $unsafe )
160 =head2 deparse( $uri )
162 Does some rudimentary deparsing of a uri based on the current template.
163 Returns a hash with the extracted values.
171 if ( !$self->{ deparse_re } ) {
172 my $templ = $self->as_string;
173 $self->{ vars_list } = [ $templ =~ /{(.+?)}/g ];
174 $templ =~ s/{.+?}/(.+?)/g;
175 $self->{ deparse_re } = qr/^${templ}$/;
178 my @matches = $uri =~ $self->{ deparse_re };
181 @results{ @{ $self->{ vars_list } } } = @matches;
187 Brian Cassidy E<lt>bricas@cpan.orgE<gt>
189 =head1 COPYRIGHT AND LICENSE
191 Copyright 2008 by Brian Cassidy
193 This library is free software; you can redistribute it and/or modify
194 it under the same terms as Perl itself.