|
-
Jan 21st, 2009, 02:06 PM
#1
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.
Last edited by wossname; Jan 21st, 2009 at 02:13 PM.
I don't live here any more.
-
Jan 22nd, 2009, 07:08 AM
#2
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.
-
Jan 22nd, 2009, 01:26 PM
#3
Re: Handy Perl tip - this is too good to miss!
I don't live here any more.
-
Feb 17th, 2009, 08:39 PM
#4
Frenzied Member
Re: Handy Perl tip - this is too good to miss!
I have that book too. And now you know that.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|