Results 1 to 4 of 4

Thread: Handy Perl tip - this is too good to miss!

Threaded View

  1. #1

    Thread Starter
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width