Is Perl *that* good?

Carl Banks imbosol at aerojockey.invalid
Wed Apr 28 02:18:41 EDT 2004


Wallclimber wrote:
> 
> 
>>     Asun> Probably the only time I would reach for Perl rather than for
>>     Asun> python is when I knew a task involved a lot of regex (and no
>>     Asun> object orientation).
>> 
>> Why?  I write non-object-oriented Python code all the time.  To make the
>> Python/Perl switch you'd still have to shift your mental gears to deal with
>> a different syntax, different way of getting at and using functionality that
>> isn't builtin, etc.  Even with lots of regex fiddling to do, I think the
>> extra overhead of using regexes in Python would be swamped by the other
>> differences.  In addition, as Jamie Zawinski suggests, regular expressions
>> are not always the best choice.
> 
> I have to agree with the original poster. My *only* complaint about
> Python are not regex search, but regex search and replace operations.
> Perl   : s =~ s/(\w+)\s*=\s*(\d+)/$2 <= $1/g;
> Python : regex.sub(s, "(\w+)\s*=\s*)\d+)", (lambda m: m.group(2)+" <=
> "+m.group(1)))
> 
> I didn't try this out so there might be some syntax problems in there,
> but you get the idea. Is there a 'nicer' way to do this in python?
> Using 'group' and lambda functions is really quite messy. (An,
> obviously, in real life usage, the replacemant function can be much
> bigger...)
> 
> I'd be most grateful if somebody could show me a cleaner way to do
> this.


Define the following helper function (mrd stands for match replace
dict, I wanted something small, call it what you want):

    def mrd(m):
        d = {}
        for i,g in enumerate(m.groups()):
            d[str(i+1)] = g
        return d


Then your regex becomes:

    regex.sub(s, "(\w+)\s*=\s*)\d+)", "%(2)s <= %(1)s" % mrd(m))


Were you aware that, when a dict appears on the right side of string
interpolation operator %, you can reference values in the dict by
name?  That's what the above trick does.  Not quite down to Perl
minimalism, but clean.


-- 
CARL BANKS                      http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work." 
          -- Parody of Mr. T from a Robert Smigel Cartoon



More information about the Python-list mailing list