Python vs. Perl, which is better to learn?

James J. Besemer jb at cascade-sys.com
Wed May 1 00:56:05 EDT 2002


Mark McEahern wrote:

> Could you give us a concrete example where the use of regular expressions in
> Perl is superior to Python?

Superior probably is too strong a word, though regex in Perl is a little easier
to get to right out of the box.  I.e, regex is part of Perl's "builtins".


PERL regex example:

        # No import, compile, function or object syntax.
        # Implied match is with the "current" thingy ( $_, IIRC)

       action() if /regex/ ;    # perform action() if regex match

To match with a specific object, say, a variable you use the "=~" operator.

    action( $a) if $a =~ /regex/ ; # perform action if regex matches $a

Note that the statement for substitute is like the "vi" command:

    $a ~ s/old/new/gi  if $a =~ /pattern1/;

        # substitue "new" for "old" in $a if $a matches pattern1
        #    g suffix for global replacement
        #    i suffix for case insensitive comparison

I personally find some of these forms to be abominations but they are highly
mnenomic to people who have used Unix for a long time.

The basic regex operators are similar to Python's, though Perl adds some extras
such as

    {n,m}    # preceeding pattern matches at least n but no more than m times

A successful match sets a flurry of global variables:

    $& = the matched portion of the input string

    $` = everything before the match

    $' = everything after the match

Parentheses in the regex break the matching pattern into "groups" and the
portions of the string coresponding to each group may be accessed via:

    $1, $2, ...

E.g.,

    s/^([^ ]* *([^ ]*)/$2 $1/;    # reverse order of 2 words

    if( /Time: (..):(..):(..)/ ){    # extract hh:mm:ss fields
        $hours = $1;
        $min = $2;
        $sec = $3;
    }



Regards

--jb

--
James J. Besemer  503-280-0838 voice
http://cascade-sys.com  503-280-0375 fax
mailto:jb at cascade-sys.com







More information about the Python-list mailing list