converting perl to python - simple questions.
Andrew Johnson
andrew-johnson at home.com
Sun Apr 25 17:19:13 EDT 1999
In article <m3u2u47hod.fsf at deneb.cygnus.stuttgart.netsurf.de>,
Florian Weimer <fw at cygnus.stuttgart.netsurf.de> wrote:
! 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.
Just a point of clarification: Actually, perl programmer's
traditionally use 'exists' to test if a key is in a hash ... using
'defined' to test for key existence is a mistake---'defined' will
only tell you if that key exists and has a defined value associated
with it: Witness the defined test on key2 in the following:
#!/usr/bin/perl -w
use strict;
my %hash = ( key1 => 0,
key2 => undef,
key3 => 1
);
print "key1 exists\n" if exists $hash{key1};
print "key1 has defined value\n" if defined $hash{key1};
print "key1 has true value\n" if $hash{key1};
print "key2 exists\n" if exists $hash{key2};
print "key2 has defined value\n" if defined $hash{key2};
print "key2 has true value\n" if $hash{key2};
print "key3 exists\n" if exists $hash{key3};
print "key3 has defined value\n" if defined $hash{key3};
print "key3 has true value\n" if $hash{key3};
__END__
which prints:
key1 exists
key1 has defined value
key2 exists
key3 exists
key3 has defined value
key3 has true value
regards
andrew
More information about the Python-list
mailing list