Handy Perl tip - this is too good to miss!
Perl 5.8 doesn't officially support proper "named capture". This is a frequent complaint from .net developers who are used to using named capture.
But you CAN fake it with a bit of nifty syntax, and it doesn't look TOO horrible either!
I found the following technique in a brilliant book called "Mastering Regular Expressions 2nd Edition" (ISBN: 0-596-00289-0)
Here's a snippet of my own devising which uses the technique to convert today's date from one format ("21-01-2009") to another ("20090121") using named capture fields.
I have highlighted the special MATCH syntax in red, and the REPLACEMENT syntax in green...
Code:
echo "21-01-2009" | perl -pe 's/(\d\d)(?{$day=$^N})-(\d\d)(?{$month=$^N})-(\d{4})(?{$year=$^N})/$year$month$day/g'
Naturally, this simple example can be achieved with the standard numbered captures (\1, \2, \3....) but having the ability to use named captures is a major compatibility bonus when comparing Perl to other regex-supporting languages.
That book is ace by the way. Highly recommended.
Re: Handy Perl tip - this is too good to miss!
Regexp::Fields appears to provide named capture for Perl versions less than 5.10 (which has it included). Doesn't appear to have been updated for a while, and I couldn't get it installed on osx leopard (perl 5.8.8) to test it.
Re: Handy Perl tip - this is too good to miss!
Re: Handy Perl tip - this is too good to miss!
I have that book too. And now you know that.