Help needed with translating perl to python
attn.steven.kuo at gmail.com
attn.steven.kuo at gmail.com
Tue Jun 26 11:59:40 EDT 2007
On Jun 26, 8:04 am, vj <vinjv... at gmail.com> wrote:
> I have a perl script which connect to network stream using sockets.
> The scripts first logins in to the server and then parses the data
> comming from the socket.
>
> Statement 1:
> my $today = sprintf("%4s%02s%02s", [localtime()]->[5]+1900,
> [localtime()]->[4]+1, [localtime()]->[3]) ;
Perl has "Do What I Mean" features that allow you to
treat strings and number interchangeably. Python's
time.localtime returns a tuple of integers so you'll
have to use the proper format conversion characters:
import time
today = "%04d%02d%02d" % time.localtime()[0:3]
# No need to add offsets of 1900 and 1 because Python
# does this for you
>
> Statement 2:
> my $password = md5_hex("$today$username") ;
You should have added that md5_hex is comes from
Digest::MD5, not a core Perl module. Regardless:
import md5
password = md5.new("%s%s" % (today, username)).hexdigest()
# seems to be what you wanted
> Statement group 3:
>
> $msglen = bcdlen(length($msg)) ;
>
> sub bcdlen {
> my $strlen = sprintf("%04s", shift) ;
> my $firstval = substr($strlen, 2, 1)*16 + substr($strlen, 3, 1) ;
> my $lastval = substr($strlen, 0, 1)*16 + substr($strlen, 1, 1) ;
> return chr($firstval) . chr($lastval) ;
>
> }
You can have a variadic function in Python but the parameters
are passed via a tuple. Because a tuple is immutable, one cannot
"shift" elements out of a tuple. Here I've used the first parameter
via selection by index. Perl's substr is replaced by slice notation;
chr is, well, chr. Concatenation (Perl's '.' operator) is replaced
by string formatting:
>>> def bcdlen(*args):
... strlen = "%04s" % str(args[0])
... firstval = int(strlen[2:3]) * 16 + int(strlen[3:4])
... lastval = int(strlen[0:1]) * 16 + int(strlen[1:2])
... return "%s%s" % (chr(firstval), chr(lastval))
...
>>> bcdlen(4546)
'FE'
--
Hope this helps,
Steven
More information about the Python-list
mailing list