64 lines
2.0 KiB
Plaintext
64 lines
2.0 KiB
Plaintext
From: andrew-johnson at home.com (Andrew Johnson)
|
|
Date: Sun, 25 Apr 1999 21:19:13 GMT
|
|
Subject: converting perl to python - simple questions.
|
|
References: <7fvagp$8lm$1@nnrp1.dejanews.com> <m3u2u47hod.fsf@deneb.cygnus.stuttgart.netsurf.de>
|
|
Message-ID: <lFLU2.3119$Ig1.434671@news1.rdc1.on.wave.home.com>
|
|
Content-Length: 1680
|
|
X-UID: 1235
|
|
|
|
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
|
|
|
|
|
|
|
|
|