[Templates] More vmethods.

Mark Mills extremely@hostile.org
Thu, 03 May 2007 21:09:45 -0400


Shouldn't list.pick be list.rand? Or, list.rand should be a synonym for 
.pick(1). Heck, I'd like hash.pick or rand too.

I love list.int. Love. I've added that (aka .round, .floor, etc.) and 
some variation of rand and pick to just about every TT thing I've done. 
Of course, now someone will want ".cast". :)

If not in TT2, then TT3 for this one.

Paul Seamons wrote:
> I've included a patch that adds several vmethods that are currently in 
> CGI::Ex::Template that I have found very, very useful.  I've included the pod 
> for the new methods in the body of this email for discussion.  The patch 
> includes code, pod, and tests for each of the new methods.
>
> Paul
>
> New Text VMethods
>   
>> =item '0'
>>
>> Essentially the same thing as the item vmethod.  Allows for items
>> to truly behave like lists - without having to call the list
>> vmethod.
>>
>>     [% thing = 'foo' %][% thing.0 %]
>>
>> =item int
>>
>> Return the integer portion of the value (0 if none).
>>
>>     [% thing.int %]
>>
>> =item fmt
>>
>> Returns a string formatted with the passed pattern.  Default pattern is %s.
>>
>> Similar to the Perl6 fmt method for scalars.  Also similar to the format 
>>     
> filter,
>   
>> but doesn't split the string on newlines like format does.
>>
>>     [% thing.fmt('%d') %]
>>     [% thing.fmt('%6s') %]
>>     [% thing.fmt('%*s', 6) %]
>>
>> =item rand
>>
>> Returns a random number greater or equal to 0 but less than the
>> item itself.
>>
>>     [% thing = 10; thing.rand %]
>>     
>
> New Hash VMethods
>
>   
>> =item fmt
>>
>> Passed a pattern and an string to join on.  Returns a string of the 
>>     
> key/value pairs
>   
>> of the hash formatted with the passed pattern and joined with the passed 
>>     
> string.
>   
>> Default pattern is "%s\t%s" and the default join string is a newline.
>>
>> Similar to the Perl6 fmt method for hashes.
>>
>>     [% myhash.fmt('%s => %s', "\n") %]
>>     [% myhash.fmt('%4s => %5s', "\n") %]
>>     [% myhash.fmt('%*s => %*s', "\n", 4, 5) %]
>>     
>
> New List VMethods
>
>   
>> =item fmt
>>
>> Passed a pattern and an string to join on.  Returns a string of the values 
>>     
> of the list
>   
>> formatted with the passed pattern and joined with the passed string.
>> Default pattern is %s and the default join string is a space.
>>
>> Similar to the Perl6 fmt method for arrays.
>>
>>     [% mylist.fmt('%s', ', ') %]
>>     [% mylist.fmt('%6s', ', ') %]
>>     [% mylist.fmt('%*s', ', ', 6) %]
>>
>> =item pick
>>
>> Returns a random item from the list.  If a numeric value is
>> passed and is greater than one, then a list of random
>> values from the array is returned (Note: the same value
>> may be returned multiple times as each pick is random).
>>
>>     [% mylist = ['a' .. 'z'] %]
>>     [% mylist.pick %]
>>     [% mylist.pick(8).join('') %]
>>