NAME

Top Close Open

Template::TT3::Type::Text - object for representing and manipulating text

SYNOPSIS

Top Close Open
use Template::TT3::Text;

my $text = Template::TT3::Text->new('Hello World');

print "length: ", $text->length(), "\n";

DESCRIPTION

Top Close Open

NOTE: this documentation is a quick cut-n-paste from an earlier version. It's incomplete and almost certainly incorrect in places. Don't trust anything you read here.

This module implements an object for representing and manipulating text strings. The methods implemented by this object are made available in templates as text virtual methods which can be called via the dot operator.

[% text = 'Hello World' %]
[% text.length %]           # 11

Text object can also be created directly for those who prefer a more strict object oriented style.

[% text = Text.new('Hello World') %]
[% text.length %]           # 11

Methods

Top Close Open

append(text)

Top Close Open

TODO: constructs and returns a new string comprising of the current text string (if defined) with the arguments appended to it.

capital

Top Close Open

TODO: capitalise first letter of text

capitals

Top Close Open

TODO: capitalise first letter of each word in text

centre(width) / center(width)

Top Close Open

TODO: center within width characters

chomp

Top Close Open

TODO: remove trailing newline

chop

Top Close Open

TODO: remove trailing character

chunk(size)

Top Close Open

This splits the text into a list of smaller chunks. The argument defines the maximum length in characters of each chunk.

[% ccard_no = "1234567824683579";
   ccard_no.chunk(4).join
%]

Output:

1234 5678 2468 3579

If the size is specified as a negative number then the text will be chunked from right-to-left. This gives the correct grouping for numbers, for example.

[% number = 1234567;
   number.chunk(-3).join(',')
%]

Output:

1,234,567

clone(text)

Top Close Open

TODO: copy the text and return a new text object. Any arguments provided are appended to the end of the cloned text object.

collapse

Top Close Open

TODO: collapsed any sequences of multiple whitespace characters into a single space.

copy

Top Close Open

TODO: return a copy of the text.

defined

Top Close Open

This returns true if the text is set to some defined value, including an empty string or the number zero. It returns false if the text is undefined.

text [% text.defined ? 'is' : 'is not' %] defined

equals(text)

Top Close Open

TODO: Return true if the text is the same as the argument passed, false otherwise.

format(format)

Top Close Open

TODO: format text using sprintf()

hash(key)

Top Close Open

This returns a hash reference containing the original item as the single entry, indexed by the key text.

[% name = 'Slartibartfast';   # define text
   user = name.hash;          # convert to hash
   user.text                  # Slartibartfast
%]     

If you want the text stored in the hash array using a different index key, then provide it as an argument.

[% name = 'Slartibartfast';   
   user = name.hash('name');
   user.name 
%]     

Any further arguments provided are also folded into the hash array.

[% name = 'Slartibartfast';   
   user = name.hash('name', age => 13479);
   user.name;               # Slartibartfast
   user.age;                # 13479
%]     

item

Top Close Open

TODO: just returns a copy of self text

left(width)

Top Close Open

TODO: format left, padded with spaces

length

Top Close Open

This virtual method returns the number of characters in the text.

[% IF password.length < 8 %]
   Your password is too short, please try again.
[% END %]

list

Top Close Open

This returns the text as a single element list.

[% list_of_thing = thing.list %]

The list virtual method can also be called against a list and will return the list itself, effectively doing nothing. Hence, if thing is already a list, then thing.list will return the original list. Either way, things ends up containing a reference to a list.

Most of the time you don't need to worry about the difference between scalars and lists. You can call a list virtual method against any scalar item and it will be treated as if it were a single element list.

The list vmethod is provided for those times when you really do want to be sure that you've got a list reference. For example, if you are calling a Perl subroutine that expects a reference to a list, then adding the .list vmethod to the argument passed to it will ensure that it is passed a reference to a list regardless.

    [% item = 'foo';
       mysub(item.list)  # same as mysub([item])
    %]                   #  - item is a scalar

    [% item = ['foo'];
       mysub(item.list)  # same as mysub(item)
    %]                   #  - item is already a list

lower

Top Close Open

TODO: return lower case version of text

match(pattern) / search(pattern) # alias

Top Close Open

The match virtual method performs a Perl regular expression match on the string using the pattern passed as an argument.

[% FOREACH serial IN ['ABC-1234', 'FOOD-4567', 'WXYZ-789'];
     IF serial.match('^\w{3}-\d{4}$');
       "GOOD serial number: $serial\n";
     ELSE;
       "BAD serial number: $serial\n";
     END;
   END
%]

Output:

GOOD serial number: ABC-1234
BAD serial number: FOOD-4567
BAD serial number: WXYZ-789

The pattern can contain parentheses to capture parts of the matched string. If the entire pattern matches then the vmethod returns a reference to a list of the captured strings.

[% name = 'Arthur Dent' %]
[% matches = name.match('(\w+) (\w+)') %]
[% matches.1 %], [% matches.join('') %]  #  Dent, ArthurDent

In this example, the match vmethod returns a list of the two strings matched by the parenthesised patterns, (\w+). Here they are the values Arthur and Dent.

Remember that match returns false if the pattern does not match. It does not return a reference to an empty list which both Perl and the Template Toolkit would treat as a true value, regardless of how many entries it contains. This allows you to test the value returned by match to determine if the pattern matched or not.

The following example shows how the results of the match vmethod can be saved in the matches variable, while also testing that the pattern matched. The assignment statement is enclosed in parenthesis and used as the expression for an IF directive.

[% IF (matches = name.match('(\w+) (\w+)')) %]
   pattern matches: [% matches.join(', ') %]
[% ELSE %]
   pattern does not match
[% END %]

Any regular expression modifiers can be embedded in the pattern using the (?imsx-imsx) syntax. For example, a case-insensitive match can be specified by using the (?i) construct at the start of the pattern:

[% matched = name.match('(?i)arthur dent') %]

In the following fragment, the (?x) flag is set to have whitespace and comments in the pattern ignored:

[% matched = name.match(
     '(?x)
        (\w+)   # match first name
         \s+    # some whitespace
        (\w+)   # match second name
     '
   )
%]

The details of Perl's regular expressions are described in the perlre(1) manpage. For a complete guide to learning and using regular expressions, see "Mastering Regular Expressions" by Jeffrey Friedl, published by O'Reilly.

prepend(text)

Top Close Open

TODO: return new text containing all the arguments prepended onto the beginning of the current text.

ref

Top Close Open

TODO: returns Template::TT3::VObject::Text, just like ref()

remove(pattern)

Top Close Open

TODO: remove from the text anything mathing the pattern passed as an argument.

repeat(count)

Top Close Open

This virtual method returns a string containing the original text repeated a number of times. The repeat value should be passed as an argument.

[% dash = '- ';
   dash.repeat(10);       # - - - - - - - - - - 
%]                

replace(search, replace)

Top Close Open

This virtual method performs a global search and replace on a copy of the text. The first argument provides a Perl regular expression to match part of the text. The second argument is the replacement value. Each occurrence of the pattern in the input string will be replaced (hence the "global" part of "global search and replace").

[% name = 'foo, bar & baz' %]
[% name.replace('\W+', '_') %]    # foo_bar_baz

The replace vmethod returns a copy of the text, leaving the original unmodified.

right(width)

Top Close Open

TODO: format right, padded with spaces

size

Top Close Open

This virtual method always returns 1 for scalar values. It is provided for consistency with the hash and list virtual methods of the same name.

split(pattern)

Top Close Open

This virtual method splits the input text into a list of strings which is then returned. It uses the regular expression passed as an argument as the delimiter, or whitespace as default if an explicit delimiter is not provided.

[% path  = '/here:/there:/every/where'; 
   paths = path.split(':');             
   paths.join(', ');           # /here, /there, /every/where
%]

text

Top Close Open

TODO: Returns the text. This de-references the object from a scalar reference to plain old scalar text. It does the same thing as copy. Dunno if we want to go into all that here...

trim

Top Close Open

TODO: trim leading and trailing whitespace

truncate(length, suffix)

Top Close Open

TODO: truncate at a certain length, adding an optional suffix.

[% text = 'blah blah blah blah';
   text.truncate(12, '...')     # blah blah bl...
%]

type

Top Close Open

TODO: Returns 'Text';

upper

Top Close Open

TODO: return UPPER CASE version of text

pop

Top Close Open

TODO: not sure about this.

push

Top Close Open

TODO: not sure about this.

shift

Top Close Open

TODO: not sure about this.

unshift

Top Close Open

TODO: not sure about this.

AUTHOR

Top Close Open

Andy Wardley http://wardley.org/

COPYRIGHT

Top Close Open

Copyright (C) 1996-2008 Andy Wardley. All Rights Reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


http://tt3.template-toolkit.org/docs/Template/TT3/Type/Text.pm last modified 2009-12-22 11:00:37