home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / VMethods.pod < prev    next >
Encoding:
Text File  |  2004-01-30  |  14.6 KB  |  530 lines

  1. #============================================================= -*-perl-*-
  2. #
  3. # Template::Manual::VMethods
  4. #
  5. # DESCRIPTION
  6. #   The Template Toolkit provides virtual methods for manipulating
  7. #   variable values. Most of them are analogous to regular Perl
  8. #   functions of the same names. This section describes the different
  9. #   virtual methods that can be applied to scalar, list and hash
  10. #   values.
  11. #
  12. # AUTHOR
  13. #   Andy Wardley  <abw@andywardley.com>
  14. #
  15. # COPYRIGHT
  16. #   Copyright (C) 1996-2001 Andy Wardley.  All Rights Reserved.
  17. #   Copyright (C) 1998-2001 Canon Research Centre Europe Ltd.
  18. #
  19. #   This module is free software; you can redistribute it and/or
  20. #   modify it under the same terms as Perl itself.
  21. #
  22. # REVISION
  23. #   
  24. #
  25. #========================================================================
  26.  
  27.  
  28. #------------------------------------------------------------------------
  29. # IMPORTANT NOTE
  30. #   This documentation is generated automatically from source
  31. #   templates.  Any changes you make here may be lost.
  32. #   The 'docsrc' documentation source bundle is available for download
  33. #   from http://www.template-toolkit.org/docs.html and contains all
  34. #   the source templates, XML files, scripts, etc., from which the
  35. #   documentation for the Template Toolkit is built.
  36. #------------------------------------------------------------------------
  37.  
  38. =head1 NAME
  39.  
  40. Template::Manual::VMethods - Virtual Methods
  41.  
  42. =head1 DESCRIPTION
  43.  
  44. The Template Toolkit provides virtual methods for manipulating variable
  45. values. Most of them are analogous to regular Perl functions of the
  46. same names. This section describes the different virtual methods that
  47. can be applied to scalar, list and hash values.
  48.  
  49. =head2 Scalar Virtual Methods
  50.  
  51. =over 4 
  52.  
  53. =item defined
  54.  
  55. Returns true if the value is defined.
  56.  
  57.     [% user = get_user(uid) IF uid.defined %]
  58.  
  59. =item length
  60.  
  61. Returns the length of the string representation of the item:
  62.  
  63.     [% IF password.length < 8 %]
  64.        Password too short, dumbass!
  65.     [% END %]
  66.  
  67. =item repeat(n)
  68.  
  69. Repeat the string a specified number of times.
  70.  
  71.     [% name = 'foo' %]
  72.     [% name.repeat(3) %]        # foofoofoo
  73.  
  74. =item replace(search, replace)
  75.  
  76. Outputs the string with all instances of the first argument (specified
  77. as a Perl regular expression) with the second.
  78.  
  79.     [% name = 'foo, bar & baz' %]
  80.     [% name.replace('\W+', '_') %]    # foo_bar_baz
  81.  
  82. =item match(pattern)
  83.  
  84. Performs a regular expression match on the string using the pattern
  85. passed as an argument.  If the pattern matches the string then the
  86. method returns a reference to a list of any strings captured within
  87. parenthesis in the pattern.
  88.  
  89.     [% name = 'Larry Wall' %]
  90.     [% matches = name.match('(\w+) (\w+)') %]
  91.     [% matches.1 %], [% matches.0 %]        # Wall, Larry
  92.  
  93. If the pattern does not match then the method returns false, rather
  94. than returning an empty list which Perl and the Template Toolkit both
  95. consider to be a true value.  This allows you to write expression like
  96. this.
  97.  
  98.     [% "We're not worthy!" IF name.match('Larry Wall') %]
  99.  
  100.     [% IF (matches = name.match('(\w+) (\w+)')) %]
  101.        pattern matches: [% matches.join(', ') %]
  102.     [% ELSE %]
  103.        pattern does not match
  104.     [% END %]
  105.  
  106. Any regex modifiers, like C</s>, should be added in the regex using
  107. the C<(?s)> syntax.  For example, to modify the regex to disregard
  108. whitespace (the C</x> switch), use:
  109.  
  110.     [% re = '(?x)
  111.                (\w+)
  112.                [ ]
  113.                (\w+)
  114.              ';
  115.       matches = name.match(re);
  116.     %]
  117.  
  118. =item search(pattern)
  119.  
  120. Performs a similar function to 'match' but simply returns true if the 
  121. string matches the regular expression pattern passed as an argument.
  122.  
  123.     [% name = 'foo bar baz' %]
  124.     [% name.search('bar') ? 'bar' : 'no bar' %]        # bar
  125.  
  126. This virtual method is now deprecated in favour of 'match'.  Move along
  127. now, there's nothing more to see here.
  128.  
  129. =item split(pattern)
  130.  
  131. Calls Perl's split() function to split a string into a list of
  132. strings.
  133.  
  134.     [% FOREACH dir = mypath.split(':') %]
  135.        [% dir %]
  136.     [% END %]
  137.  
  138. =item chunk(size)
  139.  
  140. Splits the value into a list of chunks of a certain size.
  141.  
  142.     [% ccard_no = "1234567824683579";
  143.        ccard_no.chunk(4).join
  144.     %]
  145.  
  146. Output:
  147.  
  148.     1234 5678 2468 3579
  149.  
  150. If the size is specified as a negative number then the text will
  151. be chunked from right-to-left.  This gives the correct grouping 
  152. for numbers, for example.
  153.  
  154.     [% number = 1234567;
  155.        number.chunk(-3).join(',')
  156.     %]
  157.  
  158. Output:
  159.  
  160.     1,234,567
  161.  
  162. =item list
  163.  
  164. Return the value as a single element list.  This can be useful if you
  165. have a variable which may contain a single item or a list and you want
  166. to treat them equally.  The 'list' method can be called against a list
  167. reference and will simply return the original reference, effectively
  168. a no-op.
  169.  
  170.     [% thing.list.size %]  # thing can be a scalar or a list
  171.  
  172. =item hash 
  173.  
  174. Return the value as a hash reference containing a single entry with
  175. the key 'value' indicating the original scalar value.  As with the 
  176. 'list' virtual method, this is generally used to help massage data
  177. into different formats.
  178.  
  179. =item size
  180.  
  181. Always returns 1 for scalar values.  This method is provided for 
  182. consistency with the hash and list size methods.
  183.  
  184. =back
  185.  
  186.  
  187. =head2 Hash Virtual Methods
  188.  
  189. =over 4
  190.  
  191. =item keys, values, each
  192.  
  193. The regular hash operators returning lists of keys, values or both.
  194. Note how we use a '$' prefix on the 'key' variable in this example to
  195. have it interpolated (i.e. replaced with its value) before use.
  196.  
  197.     [% FOREACH key = product.keys %]
  198.        [% key %] => [% product.$key %]
  199.     [% END %]
  200.  
  201. =item sort, nsort
  202.  
  203. Return a list of the keys, sorted alphabetically (sort) or numerically
  204. (nsort) according to the corresponding values in the hash.
  205.  
  206.     [% FOREACH n = phones.sort %]
  207.        [% phones.$n %] is [% n %],
  208.     [% END %]
  209.  
  210. =item import
  211.  
  212. The import method can be called on a hash array to import the contents
  213. of another hash array.
  214.  
  215.     [% hash1 = {
  216.        foo => 'Foo',
  217.            bar => 'Bar',
  218.        }
  219.        hash2 = {
  220.            wiz => 'Wiz',
  221.            woz => 'Woz',
  222.        }
  223.     %]
  224.  
  225.     [% hash1.import(hash2) %]
  226.     [% hash1.wiz %]            # Wiz
  227.  
  228. You can also call the import() method by itself to import a hash array
  229. into the current namespace hash.
  230.  
  231.     [% user = { id => 'lwall', name => 'Larry Wall' } %]
  232.     [% import(user) %]
  233.     [% id %]: [% name %]        # lwall: Larry Wall
  234.  
  235. =item defined, exists
  236.  
  237. Returns a true or false value if an item in the hash denoted by the key
  238. passed as an argument is defined or exists, respectively.
  239.  
  240.     [% hash.defined('somekey') ? 'yes' : 'no' %]
  241.     [% hash.exists('somekey') ? 'yes' : 'no' %]
  242.  
  243. =item size
  244.  
  245. Returns the number of key =E<gt> value pairs in the hash.
  246.  
  247. =item item
  248.  
  249. Returns an item from the hash using a key passed as an argument.
  250.  
  251.     [% hash.item('foo') %]  # same as hash.foo
  252.  
  253. =item list
  254.  
  255. Returns the contents of the hash in list form.  An argument can be
  256. passed to indicate the desired items required in the list: 'keys' to
  257. return a list of the keys (same as hash.keys), 'values' to return a
  258. list of the values (same as hash.values), or 'each' to return as list
  259. of (key, value) pairs (same as hash.each).  When called without an
  260. argument it returns a list of hash references, each of which contains
  261. a 'key' and 'value' item representing a single key =E<gt> value pair
  262. in the hash.
  263.  
  264. =back
  265.  
  266.  
  267. =head2 List Virtual Methods
  268.  
  269. =over 4
  270.  
  271. =item first, last
  272.  
  273. Returns the first/last item in the list.  The item is not removed from the 
  274. list.
  275.  
  276.     [% results.first %] to [% results.last %]
  277.  
  278. If either is given a numeric argument C<n>, they return the first or
  279. last C<n> elements:
  280.  
  281.     The first 5 results are [% results.first(5).join(", ") %].
  282.  
  283. =item size, max
  284.  
  285. Returns the size of a list (number of elements) and the maximum 
  286. index number (size - 1), respectively.
  287.  
  288.     [% results.size %] search results matched your query
  289.  
  290. =item reverse
  291.  
  292. Returns the items of the list in reverse order.
  293.  
  294.     [% FOREACH s = scores.reverse %]
  295.        ...
  296.     [% END %]
  297.  
  298. =item join
  299.  
  300. Joins the items in the list into a single string, using Perl's join 
  301. function.
  302.  
  303.     [% items.join(', ') %]
  304.  
  305. =item grep
  306.  
  307. Returns a list of the items in the list that match a regular expression
  308. pattern.
  309.  
  310.     [% FOREACH directory.files.grep('\.txt$') %]
  311.        ...
  312.     [% END %]
  313.  
  314. =item sort, nsort
  315.  
  316. Returns the items in alpha (sort) or numerical (nsort) order.
  317.  
  318.     [% library = books.sort %]
  319.  
  320. An argument can be provided to specify a search key.  Where an item in 
  321. the list is a hash reference, the search key will be used to retrieve a 
  322. value from the hash which will then be used as the comparison value.
  323. Where an item is an object which implements a method of that name, the
  324. method will be called to return a comparison value.
  325.  
  326.     [% library = books.sort('author') %]
  327.  
  328. In the example, the 'books' list can contains hash references with 
  329. an 'author' key or objects with an 'author' method.
  330.  
  331. =item unshift(item), push(item)
  332.  
  333. Adds an item to the start/end of a list.
  334.  
  335.     [% mylist.unshift('prev item') %]
  336.     [% mylist.push('next item')    %]
  337.  
  338. =item shift, pop
  339.  
  340. Removes the first/last item from the list and returns it.
  341.  
  342.     [% first = mylist.shift %]
  343.     [% last  = mylist.pop   %]
  344.  
  345. =item unique
  346.  
  347. Returns a list of the unique elements in a list, in the same order
  348. as in the list itself.
  349.  
  350.     [% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %]
  351.     [% numbers = mylist.unique %]
  352.  
  353. While this can be explicitly sorted, it is not required that the list
  354. be sorted before the unique elements are pulled out (unlike the Unix
  355. command line utility).
  356.  
  357.     [% numbers = mylist.unique.sort %]
  358.  
  359. =item merge
  360.  
  361. Returns a list composed of zero or more other lists:
  362.  
  363.     [% list_one = [ 1 2 3 ];
  364.        list_two = [ 4 5 6 ];
  365.        list_three = [ 7 8 9 ];
  366.        list_four = list_one.merge(list_two, list_three);
  367.     %]
  368.  
  369. The original lists are not modified.
  370.  
  371. =item slice(from, to)
  372.  
  373. Returns a slice of items in the list between the bounds passed as
  374. arguments.  If the second argument, 'to', isn't specified, then it
  375. defaults to the last item in the list.  The original list is not 
  376. modified.
  377.  
  378.     [% first_three = list.slice(0,2) %]
  379.  
  380.     [% last_three  = list.slice(-3, -1) %]
  381.  
  382. =item splice(offset, length, list)
  383.  
  384. Behaves just like Perl's splice() function allowing you to selectively
  385. remove and/or replace elements in a list.  It removes 'length' items
  386. from the list, starting at 'offset' and replaces them with the items
  387. in 'list'.
  388.  
  389.    [% play_game = [ 'play', 'scrabble' ];
  390.       ping_pong = [ 'ping', 'pong' ];
  391.       redundant = play_game.splice(1, 1, ping_pong);
  392.  
  393.       redundant.join;     # scrabble
  394.       play_game.join;     # play ping pong
  395.    %]
  396.  
  397. The method returns a list of the items removed by the splice.
  398. You can use the CALL directive to ignore the output if you're
  399. not planning to do anything with it.
  400.  
  401.     [% CALL play_game.splice(1, 1, ping_pong) %]
  402.  
  403. As well as providing a reference to a list of replacement values,
  404. you can pass in a list of items.
  405.  
  406.    [% CALL list.splice(-1, 0, 'foo', 'bar') %]
  407.  
  408. Be careful about passing just one item in as a replacement value.
  409. If it is a reference to a list then the contents of the list will
  410. be used.  If it's not a list, then it will be treated as a single 
  411. value.  You can use square brackets around a single item if you 
  412. need to be explicit:
  413.  
  414.   [% # push a single item, an_item
  415.      CALL list.splice(-1, 0, an_item);
  416.  
  417.      # push the items from another_list
  418.      CALL list.splice(-1, 0, another_list);
  419.  
  420.      # push a reference to another_list
  421.      CALL list.splice(-1, 0, [ another_list ]);
  422.   %]
  423.  
  424. =back
  425.  
  426. =head2 Automagic Promotion of Scalar to List for Virtual Methods
  427.  
  428. In addition to the scalar virtual methods listed in the previous
  429. section, you can also call any list virtual method against a scalar.
  430. The item will be automagically promoted to a single element list and
  431. the appropriate list virtual method will be called.  
  432.  
  433. One particular benefit of this comes when calling subroutines or
  434. object methods that return a list of items, rather than the 
  435. preferred reference to a list of items.  In this case, the 
  436. Template Toolkit automatically folds the items returned into
  437. a list.
  438.  
  439. The upshot is that you can continue to use existing Perl modules or
  440. code that returns lists of items, without having to refactor it
  441. just to keep the Template Toolkit happy (by returning references
  442. to list).  Class::DBI module is just one example of a particularly 
  443. useful module which returns values this way.
  444.  
  445. If only a single item is returned from a subroutine then the 
  446. Template Toolkit assumes it meant to return a single item (rather
  447. than a list of 1 item) and leaves it well alone, returning the
  448. single value as it is.  If you're executing a database query, 
  449. for example, you might get 1 item returned, or perhaps many 
  450. items which are then folded into a list.
  451.  
  452. The FOREACH directive will happily accept either a list or a single
  453. item which it will treat as a list.  So it's safe to write directives
  454. like this, where we assume that 'something' is bound to a subroutine
  455. which might return 1 or more items:
  456.  
  457.     [% FOREACH item = something %]
  458.        ...
  459.     [% END %]
  460.  
  461. The automagic promotion of scalars to single item lists means 
  462. that you can also use list virtual methods safely, even if you
  463. only get one item returned.  For example:
  464.  
  465.     [% something.first   %]
  466.     [% something.join    %]
  467.     [% something.reverse.join(', ') %]
  468.  
  469. Note that this is very much a last-ditch behaviour.  If the single
  470. item return is an object with a 'first' method, for example, then that
  471. will be called, as expected, in preference to the list virtual method.
  472.  
  473. =head2 Defining Custom Virtual Methods
  474.  
  475. You can define your own virtual methods for scalars, lists and hash
  476. arrays.  The Template::Stash package variables $SCALAR_OPS, $LIST_OPS
  477. and $HASH_OPS are references to hash arrays that define these virtual
  478. methods.  HASH_OPS and LIST_OPS methods are subroutines that accept a
  479. hash/list reference as the first item.  SCALAR_OPS are subroutines
  480. that accept a scalar value as the first item.  Any other arguments
  481. specified when the method is called will be passed to the subroutine.
  482.  
  483.     # load Template::Stash to make method tables visible
  484.     use Template::Stash;
  485.  
  486.     # define list method to return new list of odd numbers only
  487.     $Template::Stash::LIST_OPS->{ odd } = sub {
  488.     my $list = shift;
  489.     return [ grep { $_ % 2 } @$list ];
  490.     };
  491.  
  492. template:
  493.  
  494.     [% primes = [ 2, 3, 5, 7, 9 ] %]
  495.     [% primes.odd.join(', ') %]        # 3, 5, 7, 9
  496.  
  497. =head1 AUTHOR
  498.  
  499. Andy Wardley E<lt>abw@andywardley.comE<gt>
  500.  
  501. L<http://www.andywardley.com/|http://www.andywardley.com/>
  502.  
  503.  
  504.  
  505.  
  506. =head1 VERSION
  507.  
  508. Template Toolkit version 2.13, released on 30 January 2004.
  509.  
  510. =head1 COPYRIGHT
  511.  
  512.   Copyright (C) 1996-2004 Andy Wardley.  All Rights Reserved.
  513.   Copyright (C) 1998-2002 Canon Research Centre Europe Ltd.
  514.  
  515. This module is free software; you can redistribute it and/or
  516. modify it under the same terms as Perl itself.
  517.  
  518.  
  519.  
  520. =cut
  521.  
  522. # Local Variables:
  523. # mode: perl
  524. # perl-indent-level: 4
  525. # indent-tabs-mode: nil
  526. # End:
  527. #
  528. # vim: expandtab shiftwidth=4:
  529.