converting perl to python - simple questions.

Florian Weimer fw at cygnus.stuttgart.netsurf.de
Sun Apr 25 13:07:14 EDT 1999


sweeting at neuronet.com.my writes:

> a) Perl's "defined".
>    [perl]
>    if (defined($x{$token})
> 
>    [python]
>    if (x.has_key(token) and x[token]!=None) :

Depending on the code, you can omit the comparision to `None'.  Perl
programmers traditionally uses `defined' to test if a key is in a hash,
so your code is the correct translation if you mimic Perl's undefined
value with Python's `None', but most of the time, this is not required.

> b) RE's.
>    [perl]
>    if ($mytext !~ /^\s$/)
> 
>    [python]
>    if not (re.match('^\s$'), mytext)
                      
Your Python code unconditionally executes the `false' branch of the
`if' statement.  I hope this is the correct translation:

	# Execute this once at the beginning of the program.
	single_space = re.compile(r'^\s$')  # use a r'aw' string

        # Later on, you can try to match this regexp to a string:
        if not single_space.match(mytext):

> Since I know neither perl nor chinese, it would be nice if somebody
> could help me remove one of the variables in my debugging.

I see.  I've tried to install a Chinese text processing environment
for a friend. ;)




More information about the Python-list mailing list