On Fri, Aug 23, 2002 at 10:53:49AM -0400, Joe Johnston wrote:
> my @matches = ($str =~ /($pattern)/g);

Hmmm...

I agree with Perrin that it's easy to enlist Perl to do the things that 
TT doesn't already do, but I also think it's a blow against consistency 
and orthogonality that the core TT virtual methods allow you to match a 
regex singularly, but not globally.  After all, they're pretty much the 
same thing.

So I'm tempted to modify/augment the virtual methods to facilitate this,
but I need to think about it some more... :-)

In the mean time, there are plenty of ways to work around it.  Like 
Perrin says, you could pre-calculate the matches in Perl, or alternately,
you could re-define the virtual method(s) to do what you want.  For example,
you could change match() to accept a global flag as a second argument:

  $Template::Stash::SCALAR_OPS->{ match } = sub {
      my ($str, $search, $global) = @_;
      return $str unless defined $str and defined $search;
      my @matches = ( ($global || 0) 
                    ? ($str =~ /$search/g) 
                    : ($str =~ /$search/) );
      return @matches ? \@matches : '';
  }

  [% string.match(regex, 1).size %]

or add a new virtual method to match globally:

  $Template::Stash::SCALAR_OPS->{ matches } = sub {
      my ($str, $search) = @_;
      return $str unless defined $str and defined $search;
      my @matches = ($str =~ /$search/g);
      return scalar @matches;
  }

  [% string.matches(regex) %]

If you're writing templates where you're not already using Perl handlers
then you might like to write a plugin that defines/modifies the virtual 
method for you.

/somewhere/on/your/perl/path/Template/Plugin/VMethod/Matches.pm :

   package Template::Plugin::VMethod::Matches;
   use Template::Plugin;
   use base qw( Template::Plugin );

   sub new {
       $Template::Stash::SCALAR_OPS->{ matches } = \&matches;
       return '';
   }

   sub matches {
       ...
   }

   1;

Then you can:

   [% USE VMethod.Matches %]

   string matches [% string.matches(regex) %] times

No additional Perl required.

HTH
A


_______________________________________________
templates mailing list
[EMAIL PROTECTED]
http://www.template-toolkit.org/mailman/listinfo/templates

Reply via email to