Permalink
Browse files

Added text virtual methods: upper, lower, ucfirst, lcfirst, trim and …

…collapse
  • Loading branch information...
1 parent d97d323 commit 09e0b4819afd3ef3de216570ca38d87eb53b3586 @abw committed Feb 7, 2012
Showing with 337 additions and 198 deletions.
  1. +141 −98 lib/Template/Manual/VMethods.pod
  2. +127 −87 lib/Template/VMethods.pm
  3. +69 −13 t/vmethods/text.t
View
239 lib/Template/Manual/VMethods.pod
@@ -19,50 +19,82 @@ Template::Manual::VMethods - Virtual Methods
=head1 Scalar Virtual Methods
+=head2 chunk(size)
+
+Splits the value into a list of chunks of a certain size.
+
+ [% 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
+
+=head2 collapse
+
+Returns the text with any leading and trailing whitespace removed and any
+internal sequences of whitespace converted to a single space
+
+ [% text = " The bird\n is the word" %]
+ [% text.collapse %] # The bird is the word
+
=head2 defined
Returns true if the value is defined.
[% user = get_user(uid) IF uid.defined %]
-=head2 length
+=head2 hash
-Returns the length of the string representation of the item:
+Return the value as a hash reference containing a single entry with
+the key C<value> indicating the original scalar value. As with the
+C<list> virtual method, this is generally used to help massage data
+into different formats.
- [% IF password.length < 8 %]
- Password too short, dumbass!
- [% END %]
+=head2 lcfirst
-=head2 repeat(n)
+Returns the text with the first letter converted to lower case.
-Repeat the string a specified number of times.
+ [% word = 'BIRD' %]
+ [% word.lcfirst %] # bIRD
- [% name = 'foo' %]
- [% name.repeat(3) %] # foofoofoo
+=head2 length
-=head2 replace(search, replace)
+Returns the length of the string representation of the item:
-Outputs the string with all instances of the first argument (specified
-as a Perl regular expression) with the second.
+ [% IF password.length < 8 %]
+ Password too short, dumbass!
+ [% END %]
- [% name = 'foo, bar & baz' %]
- [% name.replace('\W+', '_') %] # foo_bar_baz
+=head2 list
-You can use C<$1>, C<$2>, etc., to reference captured parts (in parentheses)
-in the regular expression. Just be careful to I<single> quote the replacement
-string. If you use I<double> quotes then TT will try and interpolate the
-variables before passing the string to the C<replace> vmethod.
+Return the value as a single element list. This can be useful if you
+have a variable which may contain a single item or a list and you want
+to treat them equally. The C<list> method can be called against a list
+reference and will simply return the original reference, effectively
+a no-op.
- [% name = 'FooBarBaz' %]
- [% name.replace('([A-Z])', ' $1') %] # Foo Bar Baz
+ [% thing.list.size %] # thing can be a scalar or a list
-=head2 remove(pattern)
+=head2 lower
-Outputs the string with all instances of the pattern (specified
-as a Perl regular expression) removed.
+Returns the text in lower case.
- [% name = 'foo, bar & baz' %]
- [% name.remove('\W+') %] # foobarbaz
+ [% word = 'BIRD' %]
+ [% word.lower %] # bird
=head2 match(pattern, global)
@@ -73,7 +105,7 @@ parenthesis in the pattern.
[% name = 'Larry Wall' %]
[% matches = name.match('(\w+) (\w+)') %]
- [% matches.1 %], [% matches.0 %] # Wall, Larry
+ [% matches.1 %], [% matches.0 %] # Wall, Larry
If the pattern does not match then the method returns false, rather
than returning an empty list which Perl and the Template Toolkit both
@@ -101,16 +133,47 @@ whitespace (the C</x> switch), use:
%]
To perform a global search to match the pattern as many times as it
-appears in the source string, provide a true value for the C<global>
+appears in the source string, provide a true value for the C<global>
argument following the pattern.
[% text = 'bandanna';
text.match('an+', 1).join(', ) # an, ann
%]
+=head2 repeat(n)
+
+Repeat the string a specified number of times.
+
+ [% name = 'foo' %]
+ [% name.repeat(3) %] # foofoofoo
+
+=head2 replace(search, replace)
+
+Outputs the string with all instances of the first argument (specified
+as a Perl regular expression) with the second.
+
+ [% name = 'foo, bar & baz' %]
+ [% name.replace('\W+', '_') %] # foo_bar_baz
+
+You can use C<$1>, C<$2>, etc., to reference captured parts (in parentheses)
+in the regular expression. Just be careful to I<single> quote the replacement
+string. If you use I<double> quotes then TT will try and interpolate the
+variables before passing the string to the C<replace> vmethod.
+
+ [% name = 'FooBarBaz' %]
+ [% name.replace('([A-Z])', ' $1') %] # Foo Bar Baz
+
+=head2 remove(pattern)
+
+Outputs the string with all instances of the pattern (specified
+as a Perl regular expression) removed.
+
+ [% name = 'foo, bar & baz' %]
+ [% name.remove('\W+') %] # foobarbaz
+
=head2 search(pattern)
-Performs a similar function to L<match> but simply returns true if the
+Performs a similar function to L<match> but simply returns true if the
string matches the regular expression pattern passed as an argument.
[% name = 'foo bar baz' %]
@@ -119,6 +182,11 @@ string matches the regular expression pattern passed as an argument.
This virtual method is now deprecated in favour of L<match>. Move along
now, there's nothing more to see here.
+=head2 size
+
+Always returns 1 for scalar values. This method is provided for
+consistency with the hash and list size methods.
+
=head2 split(pattern)
Calls Perl's C<split()> function to split a string into a list of
@@ -128,30 +196,6 @@ strings.
[% dir %]
[% END %]
-=head2 chunk(size)
-
-Splits the value into a list of chunks of a certain size.
-
- [% 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
-
=head2 substr(offset, length, replacement)
Returns a substring starting at C<offset>, for C<length> characters.
@@ -171,33 +215,32 @@ C<$replacement>. The substring removed from the string is then returned.
[% str.substr(0, 11, 'FOO') %] # foo bar baz
[% str %] # FOO wiz waz woz
-=head2 list
+=head2 trim
-Return the value as a single element list. This can be useful if you
-have a variable which may contain a single item or a list and you want
-to treat them equally. The C<list> method can be called against a list
-reference and will simply return the original reference, effectively
-a no-op.
+Returns the text with any leading and trailing whitespace removed.
- [% thing.list.size %] # thing can be a scalar or a list
+ [% text = ' hello world ' %]
+ [% text.trim %] # hello world
-=head2 hash
+=head2 ucfirst
-Return the value as a hash reference containing a single entry with
-the key C<value> indicating the original scalar value. As with the
-C<list> virtual method, this is generally used to help massage data
-into different formats.
+Returns the text with the first letter converted to upper case.
-=head2 size
+ [% word = 'bird' %]
+ [% word.ucfirst %] # Bird
-Always returns 1 for scalar values. This method is provided for
-consistency with the hash and list size methods.
+=head2 upper
+
+Returns the text in upper case.
+
+ [% word = 'bird' %]
+ [% word.upper %] # BIRD
=head1 Hash Virtual Methods
=head2 keys
-Returns a list of keys in the hash. They are not returned in any
+Returns a list of keys in the hash. They are not returned in any
particular order, but the order is the same as for the corresponding
values method.
@@ -212,20 +255,20 @@ If you want the keys in sorted order, use the list C<sort> method.
[% END %]
Having got the keys in sorted order, you can then use variable
-interpolation to fetch the value. This is shown in the following
+interpolation to fetch the value. This is shown in the following
example by the use of C<$key> to fetch the item from C<hash> whose
key is stored in the C<key> variable.
[% FOREACH key IN hash.keys.sort %]
* [% key %] = [% hash.$key %]
[% END %]
-Alternately, you can use the C<pairs> method to get a list of
+Alternately, you can use the C<pairs> method to get a list of
key/value pairs in sorted order.
=head2 values
-Returns a list of the values in the hash. As with the C<keys> method,
+Returns a list of the values in the hash. As with the C<keys> method,
they are not returned in any particular order, although it is the same
order that the keys are returned in.
@@ -239,7 +282,7 @@ Returns a list of both the keys and the values expanded into a single list.
a = 10
b = 20
};
-
+
hash.items.join(', ') # a, 10, b, 20
%]
@@ -255,7 +298,7 @@ method more consistent with each other and how Perl works.
In anticipation of this, we recommend that you stop using C<hash.each>
and instead use C<hash.items>.
-=head2 pairs
+=head2 pairs
This method returns a list of key/value pairs. They are returned in
sorted order according to the keys.
@@ -310,7 +353,7 @@ of another hash array.
woz = 'Woz'
}
%]
-
+
[% hash1.import(hash2) %]
[% hash1.wiz %] # Wiz
@@ -332,7 +375,7 @@ passed as an argument is defined or exists, respectively.
When called without any argument, C<hash.defined> returns true if the hash
itself is defined (e.g. the same effect as C<scalar.defined>).
-=head2 delete
+=head2 delete
Delete one or more items from the hash.
@@ -352,7 +395,7 @@ Returns an item from the hash using a key passed as an argument.
=head2 first, last
-Returns the first/last item in the list. The item is not removed from the
+Returns the first/last item in the list. The item is not removed from the
list.
[% results.first %] to [% results.last %]
@@ -364,7 +407,7 @@ last C<n> elements:
=head2 size, max
-Returns the size of a list (number of elements) and the maximum
+Returns the size of a list (number of elements) and the maximum
index number (size - 1), respectively.
[% results.size %] search results matched your query
@@ -409,15 +452,15 @@ Returns the items in alpha (C<sort>) or numerical (C<nsort>) order.
[% library = books.sort %]
-An argument can be provided to specify a search key. Where an item in
-the list is a hash reference, the search key will be used to retrieve a
+An argument can be provided to specify a search key. Where an item in
+the list is a hash reference, the search key will be used to retrieve a
value from the hash which will then be used as the comparison value.
Where an item is an object which implements a method of that name, the
method will be called to return a comparison value.
[% library = books.sort('author') %]
-In the example, the C<books> list can contains hash references with
+In the example, the C<books> list can contains hash references with
an C<author> key or objects with an C<author> method.
You can also specify multiple sort keys.
@@ -433,7 +476,7 @@ The C<push()> method adds an item or items to the end of list.
[% mylist.push(foo) %]
[% mylist.push(foo, bar) %]
-
+
The C<unshift()> method adds an item or items to the start of a list.
[% mylist.unshift(foo) %]
@@ -469,7 +512,7 @@ current list.
two = [ 4 5 6 ];
three = [ 7 8 9 ];
one.import(two, three);
- one.join(', ); # 1, 2, 3, 4, 5, 6, 7, 8, 9
+ one.join(', ); # 1, 2, 3, 4, 5, 6, 7, 8, 9
%]
=head2 merge
@@ -488,7 +531,7 @@ The original lists are not modified.
Returns a slice of items in the list between the bounds passed as
arguments. If the second argument, C<to>, isn't specified, then it
-defaults to the last item in the list. The original list is not
+defaults to the last item in the list. The original list is not
modified.
[% first_three = list.slice(0,2) %]
@@ -521,21 +564,21 @@ you can pass in a list of items.
Be careful about passing just one item in as a replacement value.
If it is a reference to a list then the contents of the list will
-be used. If it's not a list, then it will be treated as a single
-value. You can use square brackets around a single item if you
+be used. If it's not a list, then it will be treated as a single
+value. You can use square brackets around a single item if you
need to be explicit:
[% # push a single item, an_item
CALL list.splice(-1, 0, an_item);
-
+
# push the items from another_list
CALL list.splice(-1, 0, another_list);
-
+
# push a reference to another_list
CALL list.splice(-1, 0, [ another_list ]);
%]
-=head2 hash
+=head2 hash
Returns a reference to a hash array comprised of the elements in the
list. The even-numbered elements (0, 2, 4, etc) become the keys and
@@ -551,33 +594,33 @@ keys generated for each item starting at the number specified.
[% list = ['beer', 'peanuts'] %]
[% hash = list.hash(1) %]
- [% hash.1 %] # beer
+ [% hash.1 %] # beer
[% hash.2 %] # peanuts
=head1 Automagic Promotion of Scalar to List for Virtual Methods
In addition to the scalar virtual methods listed in the previous
section, you can also call any list virtual method against a scalar.
The item will be automagically promoted to a single element list and
-the appropriate list virtual method will be called.
+the appropriate list virtual method will be called.
One particular benefit of this comes when calling subroutines or
-object methods that return a list of items, rather than the
-preferred reference to a list of items. In this case, the
+object methods that return a list of items, rather than the
+preferred reference to a list of items. In this case, the
Template Toolkit automatically folds the items returned into
a list.
The upshot is that you can continue to use existing Perl modules or
code that returns lists of items, without having to refactor it
just to keep the Template Toolkit happy (by returning references
-to list). C<Class::DBI> module is just one example of a particularly
+to list). C<Class::DBI> module is just one example of a particularly
useful module which returns values this way.
-If only a single item is returned from a subroutine then the
+If only a single item is returned from a subroutine then the
Template Toolkit assumes it meant to return a single item (rather
than a list of 1 item) and leaves it well alone, returning the
-single value as it is. If you're executing a database query,
-for example, you might get 1 item returned, or perhaps many
+single value as it is. If you're executing a database query,
+for example, you might get 1 item returned, or perhaps many
items which are then folded into a list.
The C<FOREACH> directive will happily accept either a list or a single item
@@ -589,7 +632,7 @@ may return one or more items:
...
[% END %]
-The automagic promotion of scalars to single item lists means
+The automagic promotion of scalars to single item lists means
that you can also use list virtual methods safely, even if you
only get one item returned. For example:
@@ -613,7 +656,7 @@ called will be passed to the subroutine.
# load Template::Stash to make method tables visible
use Template::Stash;
-
+
# define list method to return new list of odd numbers only
$Template::Stash::LIST_OPS->{ odd } = sub {
my $list = shift;
View
214 lib/Template/VMethods.pm
@@ -36,20 +36,27 @@ our $ROOT_VMETHODS = {
};
our $TEXT_VMETHODS = {
- item => \&text_item,
- list => \&text_list,
- hash => \&text_hash,
- length => \&text_length,
- size => \&text_size,
- defined => \&text_defined,
- match => \&text_match,
- search => \&text_search,
- repeat => \&text_repeat,
- replace => \&text_replace,
- remove => \&text_remove,
- split => \&text_split,
- chunk => \&text_chunk,
- substr => \&text_substr,
+ item => \&text_item,
+ list => \&text_list,
+ hash => \&text_hash,
+ length => \&text_length,
+ size => \&text_size,
+ defined => \&text_defined,
+ upper => \&text_upper,
+ lower => \&text_lower,
+ ucfirst => \&text_ucfirst,
+ lcfirst => \&text_lcfirst,
+ match => \&text_match,
+ search => \&text_search,
+ repeat => \&text_repeat,
+ replace => \&text_replace,
+ remove => \&text_remove,
+ split => \&text_split,
+ chunk => \&text_chunk,
+ substr => \&text_substr,
+ trim => \&text_trim,
+ collapse => \&text_collapse,
+
};
our $HASH_VMETHODS = {
@@ -100,15 +107,15 @@ our $LIST_VMETHODS = {
# root virtual methods
#========================================================================
-sub root_inc {
+sub root_inc {
no warnings;
- my $item = shift;
+ my $item = shift;
++$item;
}
sub root_dec {
no warnings;
- my $item = shift;
+ my $item = shift;
--$item;
}
@@ -121,26 +128,59 @@ sub text_item {
$_[0];
}
-sub text_list {
+sub text_list {
[ $_[0] ];
}
-sub text_hash {
+sub text_hash {
{ value => $_[0] };
}
-sub text_length {
+sub text_length {
length $_[0];
}
-sub text_size {
+sub text_size {
return 1;
}
-sub text_defined {
+sub text_defined {
return 1;
}
+sub text_upper {
+ return uc $_[0];
+}
+
+sub text_lower {
+ return lc $_[0];
+}
+
+sub text_ucfirst {
+ return ucfirst $_[0];
+}
+
+sub text_lcfirst {
+ return lcfirst $_[0];
+}
+
+sub text_trim {
+ for ($_[0]) {
+ s/^\s+//;
+ s/\s+$//;
+ }
+ return $_[0];
+}
+
+sub text_collapse {
+ for ($_[0]) {
+ s/^\s+//;
+ s/\s+$//;
+ s/\s+/ /g
+ }
+ return $_[0];
+}
+
sub text_match {
my ($str, $search, $global) = @_;
return $str unless defined $str and defined $search;
@@ -149,15 +189,15 @@ sub text_match {
return @matches ? \@matches : '';
}
-sub text_search {
+sub text_search {
my ($str, $pattern) = @_;
return $str unless defined $str and defined $pattern;
return $str =~ /$pattern/;
}
-sub text_repeat {
+sub text_repeat {
my ($str, $count) = @_;
- $str = '' unless defined $str;
+ $str = '' unless defined $str;
return '' unless $count;
$count ||= 1;
return $str x $count;
@@ -176,52 +216,52 @@ sub text_replace {
my ($chunk, $start, $end) = @_;
$chunk =~ s{ \\(\\|\$) | \$ (\d+) }{
$1 ? $1
- : ($2 > $#$start || $2 == 0) ? ''
+ : ($2 > $#$start || $2 == 0) ? ''
: substr($text, $start->[$2], $end->[$2] - $start->[$2]);
}exg;
$chunk;
};
if ($global) {
$text =~ s{$pattern}{ &$expand($replace, [@-], [@+]) }eg;
- }
+ }
else {
$text =~ s{$pattern}{ &$expand($replace, [@-], [@+]) }e;
}
}
else {
if ($global) {
$text =~ s/$pattern/$replace/g;
- }
+ }
else {
$text =~ s/$pattern/$replace/;
}
}
return $text;
}
-sub text_remove {
+sub text_remove {
my ($str, $search) = @_;
return $str unless defined $str and defined $search;
$str =~ s/$search//g;
return $str;
}
-
+
sub text_split {
my ($str, $split, $limit) = @_;
$str = '' unless defined $str;
-
- # we have to be very careful about spelling out each possible
+
+ # we have to be very careful about spelling out each possible
# combination of arguments because split() is very sensitive
- # to them, for example C<split(' ', ...)> behaves differently
+ # to them, for example C<split(' ', ...)> behaves differently
# to C<$space=' '; split($space, ...)>
-
+
if (defined $limit) {
- return [ defined $split
+ return [ defined $split
? split($split, $str, $limit)
: split(' ', $str, $limit) ];
}
else {
- return [ defined $split
+ return [ defined $split
? split($split, $str)
: split(' ', $str) ];
}
@@ -233,11 +273,11 @@ sub text_chunk {
$size ||= 1;
if ($size < 0) {
# sexeger! It's faster to reverse the string, search
- # it from the front and then reverse the output than to
+ # it from the front and then reverse the output than to
# search it from the end, believe it nor not!
$string = reverse $string;
$size = -$size;
- unshift(@list, scalar reverse $1)
+ unshift(@list, scalar reverse $1)
while ($string =~ /((.{$size})|(.+))/g);
}
else {
@@ -249,7 +289,7 @@ sub text_chunk {
sub text_substr {
my ($text, $offset, $length, $replacement) = @_;
$offset ||= 0;
-
+
if(defined $length) {
if (defined $replacement) {
substr( $text, $offset, $length, $replacement );
@@ -270,76 +310,76 @@ sub text_substr {
#========================================================================
-sub hash_item {
- my ($hash, $item) = @_;
+sub hash_item {
+ my ($hash, $item) = @_;
$item = '' unless defined $item;
return if $PRIVATE && $item =~ /$PRIVATE/;
$hash->{ $item };
}
-sub hash_hash {
+sub hash_hash {
$_[0];
}
-sub hash_size {
+sub hash_size {
scalar keys %{$_[0]};
}
-sub hash_each {
+sub hash_each {
# this will be changed in TT3 to do what hash_pairs() does
[ %{ $_[0] } ];
}
-sub hash_keys {
+sub hash_keys {
[ keys %{ $_[0] } ];
}
-sub hash_values {
+sub hash_values {
[ values %{ $_[0] } ];
}
sub hash_items {
[ %{ $_[0] } ];
}
-sub hash_pairs {
- [ map {
- { key => $_ , value => $_[0]->{ $_ } }
+sub hash_pairs {
+ [ map {
+ { key => $_ , value => $_[0]->{ $_ } }
}
- sort keys %{ $_[0] }
+ sort keys %{ $_[0] }
];
}
-sub hash_list {
- my ($hash, $what) = @_;
+sub hash_list {
+ my ($hash, $what) = @_;
$what ||= '';
return ($what eq 'keys') ? [ keys %$hash ]
: ($what eq 'values') ? [ values %$hash ]
: ($what eq 'each') ? [ %$hash ]
- : # for now we do what pairs does but this will be changed
+ : # for now we do what pairs does but this will be changed
# in TT3 to return [ $hash ] by default
[ map { { key => $_ , value => $hash->{ $_ } } }
- sort keys %$hash
+ sort keys %$hash
];
}
-sub hash_exists {
+sub hash_exists {
exists $_[0]->{ $_[1] };
}
-sub hash_defined {
- # return the item requested, or 1 if no argument
+sub hash_defined {
+ # return the item requested, or 1 if no argument
# to indicate that the hash itself is defined
my $hash = shift;
return @_ ? defined $hash->{ $_[0] } : 1;
}
-sub hash_delete {
- my $hash = shift;
+sub hash_delete {
+ my $hash = shift;
delete $hash->{ $_ } for @_;
}
-sub hash_import {
+sub hash_import {
my ($hash, $imp) = @_;
$imp = {} unless ref $imp eq 'HASH';
@$hash{ keys %$imp } = values %$imp;
@@ -366,56 +406,56 @@ sub list_item {
$_[0]->[ $_[1] || 0 ];
}
-sub list_list {
+sub list_list {
$_[0];
}
-sub list_hash {
+sub list_hash {
my $list = shift;
if (@_) {
my $n = shift || 0;
- return { map { ($n++, $_) } @$list };
+ return { map { ($n++, $_) } @$list };
}
no warnings;
return { @$list };
}
sub list_push {
- my $list = shift;
- push(@$list, @_);
+ my $list = shift;
+ push(@$list, @_);
return '';
}
sub list_pop {
- my $list = shift;
+ my $list = shift;
pop(@$list);
}
sub list_unshift {
- my $list = shift;
- unshift(@$list, @_);
+ my $list = shift;
+ unshift(@$list, @_);
return '';
}
sub list_shift {
- my $list = shift;
+ my $list = shift;
shift(@$list);
}
sub list_max {
no warnings;
- my $list = shift;
- $#$list;
+ my $list = shift;
+ $#$list;
}
sub list_size {
no warnings;
- my $list = shift;
- $#$list + 1;
+ my $list = shift;
+ $#$list + 1;
}
sub list_defined {
- # return the item requested, or 1 if no argument to
+ # return the item requested, or 1 if no argument to
# indicate that the hash itself is defined
my $list = shift;
return 1 unless @_; # list.defined is always true
@@ -436,7 +476,7 @@ sub list_last {
}
sub list_reverse {
- my $list = shift;
+ my $list = shift;
[ reverse @$list ];
}
@@ -447,8 +487,8 @@ sub list_grep {
}
sub list_join {
- my ($list, $joint) = @_;
- join(defined $joint ? $joint : ' ',
+ my ($list, $joint) = @_;
+ join(defined $joint ? $joint : ' ',
map { defined $_ ? $_ : '' } @$list);
}
@@ -465,7 +505,7 @@ sub _list_sort_make_key {
else {
@keys = $item;
}
-
+
# ugly hack to generate a single string using a delimiter that is
# unlikely (but not impossible) to be found in the wild.
return lc join('/*^UNLIKELY^*/', map { defined $_ ? $_ : '' } @keys);
@@ -474,37 +514,37 @@ sub _list_sort_make_key {
sub list_sort {
my ($list, @fields) = @_;
return $list unless @$list > 1; # no need to sort 1 item lists
- return [
- @fields # Schwartzian Transform
+ return [
+ @fields # Schwartzian Transform
? map { $_->[0] } # for case insensitivity
sort { $a->[1] cmp $b->[1] }
map { [ $_, _list_sort_make_key($_, \@fields) ] }
@$list
: map { $_->[0] }
sort { $a->[1] cmp $b->[1] }
- map { [ $_, lc $_ ] }
+ map { [ $_, lc $_ ] }
@$list,
];
}
sub list_nsort {
my ($list, @fields) = @_;
return $list unless @$list > 1; # no need to sort 1 item lists
- return [
- @fields # Schwartzian Transform
+ return [
+ @fields # Schwartzian Transform
? map { $_->[0] } # for case insensitivity
sort { $a->[1] <=> $b->[1] }
map { [ $_, _list_sort_make_key($_, \@fields) ] }
- @$list
+ @$list
: map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
- map { [ $_, lc $_ ] }
+ map { [ $_, lc $_ ] }
@$list,
];
}
sub list_unique {
- my %u;
+ my %u;
[ grep { ++$u{$_} == 1 } @{$_[0]} ];
}
@@ -531,7 +571,7 @@ sub list_slice {
sub list_splice {
my ($list, $offset, $length, @replace) = @_;
if (@replace) {
- # @replace can contain a list of multiple replace items, or
+ # @replace can contain a list of multiple replace items, or
# be a single reference to a list
@replace = @{ $replace[0] }
if @replace == 1 && ref $replace[0] eq 'ARRAY';
View
82 t/vmethods/text.t
@@ -38,8 +38,8 @@ my $tt = Template->new();
my $tc = $tt->context();
# define vmethods using define_vmethod() interface.
-$tc->define_vmethod( item =>
- commas =>
+$tc->define_vmethod( item =>
+ commas =>
$Template::Stash::SCALAR_OPS->{ commify } );
my $params = {
@@ -49,6 +49,9 @@ my $params = {
animal => 'cat',
string => 'The cat sat on the mat',
spaced => ' The dog sat on the log',
+ word => 'bird', # The bird is the word
+ WORD => 'BIRD',
+ the_bird => "\n The bird\n is the word \n ",
};
test_expect(\*DATA, undef, $params);
@@ -60,123 +63,176 @@ __DATA__
#------------------------------------------------------------------------
-- test --
+-- name text.defined implicit undef --
[% notdef.defined ? 'def' : 'undef' %]
-- expect --
undef
-- test --
+-- name text.defined explicit undef --
[% undef.defined ? 'def' : 'undef' %]
-- expect --
undef
-- test --
+-- name text.defined zero --
[% zero.defined ? 'def' : 'undef' %]
-- expect --
def
-- test --
+-- name text.defined one --
[% one.defined ? 'def' : 'undef' %]
-- expect --
def
-- test --
+-- name string.length --
[% string.length %]
-- expect --
22
-- test --
+-- name text.upper --
+[% string.upper %]
+-- expect --
+THE CAT SAT ON THE MAT
+
+-- test --
+-- name text.lower --
+[% string.lower %]
+-- expect --
+the cat sat on the mat
+
+-- test --
+-- name text.ucfirst --
+[% word.ucfirst %]
+[% WORD.ucfirst %]
+[% WORD.lower.ucfirst %]
+-- expect --
+Bird
+BIRD
+Bird
+
+-- test --
+-- name text.lcfirst --
+[% word.lcfirst %]
+[% WORD.lcfirst %]
+-- expect --
+bird
+bIRD
+
+-- test --
+-- name text.trim --
+>[% the_bird.trim %]<
+-- expect --
+>The bird
+ is the word<
+
+-- test --
+-- name text.collapse --
+>[% the_bird.collapse %]<
+-- expect --
+>The bird is the word<
+
+-- test --
+-- name text.sort.join --
[% string.sort.join %]
-- expect --
The cat sat on the mat
-- test --
+-- name text.split.join a --
[% string.split.join('_') %]
-- expect --
The_cat_sat_on_the_mat
-- test --
+-- name text.split.join b --
[% string.split(' ', 3).join('_') %]
-- expect --
The_cat_sat on the mat
-- test --
+-- name text.split.join c --
[% spaced.split.join('_') %]
-- expect --
The_dog_sat_on_the_log
-- test --
+-- name text.split.join d --
[% spaced.split(' ').join('_') %]
-- expect --
__The_dog_sat_on_the_log
-- test --
--- name: text.list --
+-- name text.list --
[% string.list.join %]
-- expect --
The cat sat on the mat
-- test --
--- name: text.hash --
+-- name text.hash --
[% string.hash.value %]
-- expect --
The cat sat on the mat
-- test --
--- name: text.size --
+-- name text.size --
[% string.size %]
-- expect --
1
-- test --
--- name: text.repeat --
+-- name text.repeat --
[% animal.repeat(3) %]
-- expect --
catcatcat
-- test --
--- name: text.search --
+-- name text.search --
[% animal.search('at$') ? "found 'at\$'" : "didn't find 'at\$'" %]
-- expect --
found 'at$'
-- test --
--- name: text.search --
+-- name text.search --
[% animal.search('^at') ? "found '^at'" : "didn't find '^at'" %]
-- expect --
didn't find '^at'
-- test --
--- name: text.match an --
+-- name text.match an --
[% text = 'bandanna';
text.match('an') ? 'match' : 'no match'
%]
-- expect --
match
-- test --
--- name: text.match on --
+-- name text.match on --
[% text = 'bandanna';
text.match('on') ? 'match' : 'no match'
%]
-- expect --
no match
-- test --
--- name: text.match global an --
+-- name text.match global an --
[% text = 'bandanna';
text.match('an', 1).size %] matches
-- expect --
2 matches
-- test --
--- name: text.match global an --
+-- name text.match global an --
[% text = 'bandanna' -%]
matches are [% text.match('an+', 1).join(', ') %]
-- expect --
matches are an, ann
-- test --
--- name: text.match global on --
+-- name text.match global on --
[% text = 'bandanna';
text.match('on+', 1) ? 'match' : 'no match'
%]

0 comments on commit 09e0b48

Please sign in to comment.