Add built local::lib
[catagits/Gitalist.git] / local-lib5 / lib / perl5 / i486-linux-gnu-thread-multi / Template / Manual / VMethods.pod
CommitLineData
3fea05b9 1#============================================================= -*-perl-*-
2#
3# Template::Manual::VMethods
4#
5# AUTHOR
6# Andy Wardley <abw@wardley.org>
7#
8# COPYRIGHT
9# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
10#
11# This module is free software; you can redistribute it and/or
12# modify it under the same terms as Perl itself.
13#
14#========================================================================
15
16=head1 NAME
17
18Template::Manual::VMethods - Virtual Methods
19
20=head1 Scalar Virtual Methods
21
22=head2 defined
23
24Returns true if the value is defined.
25
26 [% user = get_user(uid) IF uid.defined %]
27
28=head2 length
29
30Returns the length of the string representation of the item:
31
32 [% IF password.length < 8 %]
33 Password too short, dumbass!
34 [% END %]
35
36=head2 repeat(n)
37
38Repeat the string a specified number of times.
39
40 [% name = 'foo' %]
41 [% name.repeat(3) %] # foofoofoo
42
43=head2 replace(search, replace)
44
45Outputs the string with all instances of the first argument (specified
46as a Perl regular expression) with the second.
47
48 [% name = 'foo, bar & baz' %]
49 [% name.replace('\W+', '_') %] # foo_bar_baz
50
51You can use C<$1>, C<$2>, etc., to reference captured parts (in parentheses)
52in the regular expression. Just be careful to I<single> quote the replacement
53string. If you use I<double> quotes then TT will try and interpolate the
54variables before passing the string to the C<replace> vmethod.
55
56 [% name = 'FooBarBaz' %]
57 [% name.replace('([A-Z])', ' $1') %] # Foo Bar Baz
58
59=head2 remove(pattern)
60
61Outputs the string with all instances of the pattern (specified
62as a Perl regular expression) removed.
63
64 [% name = 'foo, bar & baz' %]
65 [% name.remove('\W+') %] # foobarbaz
66
67=head2 match(pattern, global)
68
69Performs a regular expression match on the string using the pattern
70passed as an argument. If the pattern matches the string then the
71method returns a reference to a list of any strings captured within
72parenthesis in the pattern.
73
74 [% name = 'Larry Wall' %]
75 [% matches = name.match('(\w+) (\w+)') %]
76 [% matches.1 %], [% matches.0 %] # Wall, Larry
77
78If the pattern does not match then the method returns false, rather
79than returning an empty list which Perl and the Template Toolkit both
80consider to be a true value. This allows you to write expression like
81this.
82
83 [% "We're not worthy!" IF name.match('Larry Wall') %]
84
85 [% IF (matches = name.match('(\w+) (\w+)')) %]
86 pattern matches: [% matches.join(', ') %]
87 [% ELSE %]
88 pattern does not match
89 [% END %]
90
91Any regex modifiers, like C</s>, should be added in the regex using
92the C<(?s)> syntax. For example, to modify the regex to disregard
93whitespace (the C</x> switch), use:
94
95 [% re = '(?x)
96 (\w+)
97 [ ]
98 (\w+)
99 ';
100 matches = name.match(re);
101 %]
102
103To perform a global search to match the pattern as many times as it
104appears in the source string, provide a true value for the C<global>
105argument following the pattern.
106
107 [% text = 'bandanna';
108 text.match('an+', 1).join(', ) # an, ann
109 %]
110
111=head2 search(pattern)
112
113Performs a similar function to L<match> but simply returns true if the
114string matches the regular expression pattern passed as an argument.
115
116 [% name = 'foo bar baz' %]
117 [% name.search('bar') ? 'bar' : 'no bar' %] # bar
118
119This virtual method is now deprecated in favour of L<match>. Move along
120now, there's nothing more to see here.
121
122=head2 split(pattern)
123
124Calls Perl's C<split()> function to split a string into a list of
125strings.
126
127 [% FOREACH dir IN mypath.split(':') %]
128 [% dir %]
129 [% END %]
130
131=head2 chunk(size)
132
133Splits the value into a list of chunks of a certain size.
134
135 [% ccard_no = "1234567824683579";
136 ccard_no.chunk(4).join
137 %]
138
139Output:
140
141 1234 5678 2468 3579
142
143If the size is specified as a negative number then the text will
144be chunked from right-to-left. This gives the correct grouping
145for numbers, for example.
146
147 [% number = 1234567;
148 number.chunk(-3).join(',')
149 %]
150
151Output:
152
153 1,234,567
154
155=head2 substr(offset, length, replacement)
156
157Returns a substring starting at C<offset>, for C<length> characters.
158
159 [% str 'foo bar baz wiz waz woz') %]
160 [% str.substr(4, 3) %] # bar
161
162If C<length> is not specified then it returns everything from the
163C<offset> to the end of the string.
164
165 [% str.substr(12) %] # wiz waz woz
166
167If both C<length> and C<replacement> are specified, then the method
168replaces everything from C<offset> for C<length> characters with
169C<$replacement>. The substring removed from the string is then returned.
170
171 [% str.substr(0, 11, 'FOO') %] # foo bar baz
172 [% str %] # FOO wiz waz woz
173
174=head2 list
175
176Return the value as a single element list. This can be useful if you
177have a variable which may contain a single item or a list and you want
178to treat them equally. The C<list> method can be called against a list
179reference and will simply return the original reference, effectively
180a no-op.
181
182 [% thing.list.size %] # thing can be a scalar or a list
183
184=head2 hash
185
186Return the value as a hash reference containing a single entry with
187the key C<value> indicating the original scalar value. As with the
188C<list> virtual method, this is generally used to help massage data
189into different formats.
190
191=head2 size
192
193Always returns 1 for scalar values. This method is provided for
194consistency with the hash and list size methods.
195
196=head1 Hash Virtual Methods
197
198=head2 keys
199
200Returns a list of keys in the hash. They are not returned in any
201particular order, but the order is the same as for the corresponding
202values method.
203
204 [% FOREACH key IN hash.keys %]
205 * [% key %]
206 [% END %]
207
208If you want the keys in sorted order, use the list C<sort> method.
209
210 [% FOREACH key IN hash.keys.sort %]
211 * [% key %]
212 [% END %]
213
214Having got the keys in sorted order, you can then use variable
215interpolation to fetch the value. This is shown in the following
216example by the use of C<$key> to fetch the item from C<hash> whose
217key is stored in the C<key> variable.
218
219 [% FOREACH key IN hash.keys.sort %]
220 * [% key %] = [% hash.$key %]
221 [% END %]
222
223Alternately, you can use the C<pairs> method to get a list of
224key/value pairs in sorted order.
225
226=head2 values
227
228Returns a list of the values in the hash. As with the C<keys> method,
229they are not returned in any particular order, although it is the same
230order that the keys are returned in.
231
232 [% hash.values.join(', ') %]
233
234=head2 items
235
236Returns a list of both the keys and the values expanded into a single list.
237
238 [% hash = {
239 a = 10
240 b = 20
241 };
242
243 hash.items.join(', ') # a, 10, b, 20
244 %]
245
246=head2 each
247
248This method currently returns the same thing as the C<items> method.
249
250However, please note that this method will change in the next major
251version of the Template Toolkit (v3) to return the same thing as the
252C<pairs> method. This will be done in an effort to make these virtual
253method more consistent with each other and how Perl works.
254
255In anticipation of this, we recommend that you stop using C<hash.each>
256and instead use C<hash.items>.
257
258=head2 pairs
259
260This method returns a list of key/value pairs. They are returned in
261sorted order according to the keys.
262
263 [% FOREACH pair IN product.pairs %]
264 * [% pair.key %] is [% pair.value %]
265 [% END %]
266
267=head2 list
268
269Returns the contents of the hash in list form. An argument can be
270passed to indicate the desired items required in the list: C<keys> to
271return a list of the keys (same as C<hash.keys>), C<values> to return a
272list of the values (same as C<hash.values>), C<each> to return as list
273of key and values (same as C<hash.each>), or C<pairs> to return a list
274of key/value pairs (same as C<hash.pairs>).
275
276 [% keys = hash.list('keys') %]
277 [% values = hash.list('values') %]
278 [% items = hash.list('each') %]
279 [% pairs = hash.list('pairs') %]
280
281When called without an argument it currently returns the same thing as
282the C<pairs> method. However, please note that this method will change
283in the next major version of the Template Toolkit (v3) to return a
284reference to a list containing the single hash reference (as per the
285scalar list method).
286
287In anticipation of this, we recommend that you stop using C<hash.list>
288and instead use C<hash.pairs>.
289
290=head2 sort, nsort
291
292Return a list of the keys, sorted alphabetically (C<sort>) or numerically
293(C<nsort>) according to the corresponding values in the hash.
294
295 [% FOREACH n IN phones.sort %]
296 [% phones.$n %] is [% n %],
297 [% END %]
298
299=head2 import
300
301The C<import> method can be called on a hash array to import the contents
302of another hash array.
303
304 [% hash1 = {
305 foo = 'Foo'
306 bar = 'Bar'
307 }
308 hash2 = {
309 wiz = 'Wiz'
310 woz = 'Woz'
311 }
312 %]
313
314 [% hash1.import(hash2) %]
315 [% hash1.wiz %] # Wiz
316
317You can also call the C<import()> method by itself to import a hash array
318into the current namespace hash.
319
320 [% user = { id => 'lwall', name => 'Larry Wall' } %]
321 [% import(user) %]
322 [% id %]: [% name %] # lwall: Larry Wall
323
324=head2 defined, exists
325
326Returns a true or false value if an item in the hash denoted by the key
327passed as an argument is defined or exists, respectively.
328
329 [% hash.defined('somekey') ? 'yes' : 'no' %]
330 [% hash.exists('somekey') ? 'yes' : 'no' %]
331
332When called without any argument, C<hash.defined> returns true if the hash
333itself is defined (e.g. the same effect as C<scalar.defined>).
334
335=head2 delete
336
337Delete one or more items from the hash.
338
339 [% hash.delete('foo', 'bar') %]
340
341=head2 size
342
343Returns the number of key/value pairs in the hash.
344
345=head2 item
346
347Returns an item from the hash using a key passed as an argument.
348
349 [% hash.item('foo') %] # same as hash.foo
350
351=head1 List Virtual Methods
352
353=head2 first, last
354
355Returns the first/last item in the list. The item is not removed from the
356list.
357
358 [% results.first %] to [% results.last %]
359
360If either is given a numeric argument C<n>, they return the first or
361last C<n> elements:
362
363 The first 5 results are [% results.first(5).join(", ") %].
364
365=head2 size, max
366
367Returns the size of a list (number of elements) and the maximum
368index number (size - 1), respectively.
369
370 [% results.size %] search results matched your query
371
372=head2 defined
373
374Returns a true or false value if the item in the list denoted by the
375argument is defined.
376
377 [% list.defined(3) ? 'yes' : 'no' %]
378
379When called without any argument, C<list.defined> returns true if the list
380itself is defined (e.g. the same effect as C<scalar.defined>).
381
382=head2 reverse
383
384Returns the items of the list in reverse order.
385
386 [% FOREACH s IN scores.reverse %]
387 ...
388 [% END %]
389
390=head2 join
391
392Joins the items in the list into a single string, using Perl's C<join()>
393function.
394
395 [% items.join(', ') %]
396
397=head2 grep
398
399Returns a list of the items in the list that match a regular expression
400pattern.
401
402 [% FOREACH directory.files.grep('\.txt$') %]
403 ...
404 [% END %]
405
406=head2 sort, nsort
407
408Returns the items in alpha (C<sort>) or numerical (C<nsort>) order.
409
410 [% library = books.sort %]
411
412An argument can be provided to specify a search key. Where an item in
413the list is a hash reference, the search key will be used to retrieve a
414value from the hash which will then be used as the comparison value.
415Where an item is an object which implements a method of that name, the
416method will be called to return a comparison value.
417
418 [% library = books.sort('author') %]
419
420In the example, the C<books> list can contains hash references with
421an C<author> key or objects with an C<author> method.
422
423You can also specify multiple sort keys.
424
425 [% library = books.sort('author', 'title') %]
426
427In this case the books will be sorted primarily by author. If two or more
428books have authors with the same name then they will be sorted by title.
429
430=head2 unshift(item), push(item)
431
432The C<push()> method adds an item or items to the end of list.
433
434 [% mylist.push(foo) %]
435 [% mylist.push(foo, bar) %]
436
437The C<unshift()> method adds an item or items to the start of a list.
438
439 [% mylist.unshift(foo) %]
440 [% mylist.push(foo, bar) %]
441
442=head2 shift, pop
443
444Removes the first/last item from the list and returns it.
445
446 [% first = mylist.shift %]
447 [% last = mylist.pop %]
448
449=head2 unique
450
451Returns a list of the unique elements in a list, in the same order
452as in the list itself.
453
454 [% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %]
455 [% numbers = mylist.unique %]
456
457While this can be explicitly sorted, it is not required that the list
458be sorted before the unique elements are pulled out (unlike the Unix
459command line utility).
460
461 [% numbers = mylist.unique.sort %]
462
463=head2 import
464
465Appends the contents of one or more other lists to the end of the
466current list.
467
468 [% one = [ 1 2 3 ];
469 two = [ 4 5 6 ];
470 three = [ 7 8 9 ];
471 one.import(two, three);
472 one.join(', ); # 1, 2, 3, 4, 5, 6, 7, 8, 9
473 %]
474
475=head2 merge
476
477Returns a list composed of zero or more other lists:
478
479 [% list_one = [ 1 2 3 ];
480 list_two = [ 4 5 6 ];
481 list_three = [ 7 8 9 ];
482 list_four = list_one.merge(list_two, list_three);
483 %]
484
485The original lists are not modified.
486
487=head2 slice(from, to)
488
489Returns a slice of items in the list between the bounds passed as
490arguments. If the second argument, C<to>, isn't specified, then it
491defaults to the last item in the list. The original list is not
492modified.
493
494 [% first_three = list.slice(0,2) %]
495 [% last_three = list.slice(-3, -1) %]
496
497=head2 splice(offset, length, list)
498
499Behaves just like Perl's C<splice()> function allowing you to selectively
500remove and/or replace elements in a list. It removes C<length> items
501from the list, starting at C<offset> and replaces them with the items
502in C<list>.
503
504 [% play_game = [ 'play', 'scrabble' ];
505 ping_pong = [ 'ping', 'pong' ];
506 redundant = play_game.splice(1, 1, ping_pong);
507 redundant.join; # scrabble
508 play_game.join; # play ping pong
509 %]
510
511The method returns a list of the items removed by the splice.
512You can use the C<CALL> directive to ignore the output if you're
513not planning to do anything with it.
514
515 [% CALL play_game.splice(1, 1, ping_pong) %]
516
517As well as providing a reference to a list of replacement values,
518you can pass in a list of items.
519
520 [% CALL list.splice(-1, 0, 'foo', 'bar') %]
521
522Be careful about passing just one item in as a replacement value.
523If it is a reference to a list then the contents of the list will
524be used. If it's not a list, then it will be treated as a single
525value. You can use square brackets around a single item if you
526need to be explicit:
527
528 [% # push a single item, an_item
529 CALL list.splice(-1, 0, an_item);
530
531 # push the items from another_list
532 CALL list.splice(-1, 0, another_list);
533
534 # push a reference to another_list
535 CALL list.splice(-1, 0, [ another_list ]);
536 %]
537
538=head2 hash
539
540Returns a reference to a hash array comprised of the elements in the
541list. The even-numbered elements (0, 2, 4, etc) become the keys and
542the odd-numbered elements (1, 3, 5, etc) the values.
543
544 [% list = ['pi', 3.14, 'e', 2.718] %]
545 [% hash = list.hash %]
546 [% hash.pi %] # 3.14
547 [% hash.e %] # 2.718
548
549If a numerical argument is provided then the hash returned will have
550keys generated for each item starting at the number specified.
551
552 [% list = ['beer', 'peanuts'] %]
553 [% hash = list.hash(1) %]
554 [% hash.1 %] # beer
555 [% hash.2 %] # peanuts
556
557=head1 Automagic Promotion of Scalar to List for Virtual Methods
558
559In addition to the scalar virtual methods listed in the previous
560section, you can also call any list virtual method against a scalar.
561The item will be automagically promoted to a single element list and
562the appropriate list virtual method will be called.
563
564One particular benefit of this comes when calling subroutines or
565object methods that return a list of items, rather than the
566preferred reference to a list of items. In this case, the
567Template Toolkit automatically folds the items returned into
568a list.
569
570The upshot is that you can continue to use existing Perl modules or
571code that returns lists of items, without having to refactor it
572just to keep the Template Toolkit happy (by returning references
573to list). C<Class::DBI> module is just one example of a particularly
574useful module which returns values this way.
575
576If only a single item is returned from a subroutine then the
577Template Toolkit assumes it meant to return a single item (rather
578than a list of 1 item) and leaves it well alone, returning the
579single value as it is. If you're executing a database query,
580for example, you might get 1 item returned, or perhaps many
581items which are then folded into a list.
582
583The C<FOREACH> directive will happily accept either a list or a single item
584which it will treat as a list. So it's safe to write directives like this,
585where we assume that the C<something> variable is bound to a subroutine which
586may return one or more items:
587
588 [% FOREACH item IN something %]
589 ...
590 [% END %]
591
592The automagic promotion of scalars to single item lists means
593that you can also use list virtual methods safely, even if you
594only get one item returned. For example:
595
596 [% something.first %]
597 [% something.join %]
598 [% something.reverse.join(', ') %]
599
600Note that this is very much a last-ditch behaviour. If the single
601item return is an object with a C<first> method, for example, then that
602will be called, as expected, in preference to the list virtual method.
603
604=head1 Defining Custom Virtual Methods
605
606You can define your own virtual methods for scalars, lists and hash arrays.
607The L<Template::Stash> package variables C<$SCALAR_OPS>, C<$LIST_OPS> and
608C<$HASH_OPS> are references to hash arrays that define these virtual methods.
609C<HASH_OPS> and C<LIST_OPS> methods are subroutines that accept a hash/list
610reference as the first item. C<SCALAR_OPS> are subroutines that accept a scalar
611value as the first item. Any other arguments specified when the method is
612called will be passed to the subroutine.
613
614 # load Template::Stash to make method tables visible
615 use Template::Stash;
616
617 # define list method to return new list of odd numbers only
618 $Template::Stash::LIST_OPS->{ odd } = sub {
619 my $list = shift;
620 return [ grep { $_ % 2 } @$list ];
621 };
622
623Example template:
624
625 [% primes = [ 2, 3, 5, 7, 9 ] %]
626 [% primes.odd.join(', ') %] # 3, 5, 7, 9
627
628TODO: document the define_vmethod() method which makes this even easier
629
630=cut
631
632# Local Variables:
633# mode: perl
634# perl-indent-level: 4
635# indent-tabs-mode: nil
636# End:
637#
638# vim: expandtab shiftwidth=4: