On Fri, Jan 25, 2002 at 06:32:05AM -0800, Randal L. Schwartz wrote:
> I couldn't easily think of a way to adapt this to substitutions, but
> you can do this:
> 
>         my @matches = $string =~ /(\w+)\s+(\w+)/;

Please hold while I go and kick myself.

KICK.  KICK.  KICK.  KICKETY-KICK-KICK

Wood.  Trees.  Pot.  Kettle.  Short term memory loss.

Thanks Randal.  :-)

> In fact, you could
> just return that array from a "matches", and let me capture it
> and play with it.  Then if I want to do a fancy replacement, I could
> do this:
> 
>         [% m = string.matches('(.*?)(\w+)\s+(\w+)(.*)');
>            m.0; m.2; " "; m.1; m.3 %]
> 
> which swaps the first two \w+ words.  How about that? Can we have that?

Yes, you can have this.  :-)

I can't shove it back into CVS at the moment due to being stuck behind 
a firewall, but here's the change to Template::Stash

--- perl/modules/Template/Template-Toolkit-2.06d/lib/Template/Stash.pm  Tue Jan 22 
18:09:32 2002
+++ tt2/lib/Template/Stash.pm   Fri Jan 25 14:56:52 2002
@@ -75,6 +75,12 @@
 #       eval "\$str =~ s$search$replaceg";
         return $str;
     },
+    'match' => sub {
+        my ($str, $search) = @_;
+        return $str unless defined $str and defined $search;
+        my @matches = ($str =~ /$search/);
+        return @matches ? \@matches : '';
+    },
     'split'   => sub { 
         my ($str, $split, @args) = @_;
         $str = '' unless defined $str;


Note that it return an empty value rather than an empty list if the match
fails.  This allows you to do things like:

  [% IF string.match(...) %]

or

  [% IF (matches = string.match(...)) %]

and so on.


Enjoy
A



Reply via email to