Help needed with translating perl to python

Jay Loden python at jayloden.com
Tue Jun 26 11:34:54 EDT 2007


vj wrote:
> I posted too soon:
> 
>> Statement 1:
>>   my $today = sprintf("%4s%02s%02s", [localtime()]->[5]+1900,
>> [localtime()]->[4]+1, [localtime()]->[3]) ;
> 
> 1. is localtime the same as time in python?

http://perldoc.perl.org/functions/localtime.html

It's more like time.localtime()

One key thing you'll notice here is the adding of 1900 - the year returned by Perl's localtime is 'number of years since 1900' so in order to convert it to the actual year you have to add 1900.

> 2. What does -> ? do in perl?

In this case, it's accessing localtime similar to something like localtime[5]. -> can basically be considered similar to dotted notation in Python, used to access items in a container object.

> 3. What is 'my'

http://perldoc.perl.org/functions/my.html

It's a way of declaring a local variable in Perl. 

>> Statement 2:
>>   my $password = md5_hex("$today$username") ;
> 
> is md5_hex the same as md5.new(key).hexdigest() in python?

http://www.xav.com/perl/site/lib/Digest/MD5.html#functions

>> $msglen = bcdlen(length($msg)) ;
> 
> 1. here the funciton is being called with the length of variable msg.
> However the function def below does not have any args
> 
>> 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) ;
>>
>> }

Perl subroutines (functions) can be declared without any arguments if desired, and then you can use 'shift' to access any arguments. So:

sub printMe {
  my $arg = shift;
  print $arg;
}

would print the first argument passed to it, e.g. printMe("foo"); would output foo. 

> 
> 2. What does shift do above?

http://perldoc.perl.org/functions/shift.html

See above, it's used for accessing the first value of an array, in this case an arry of arguments to a subroutine.

> 3. is the '.' operator just + in python?

'.' operator is used for string concatenation in Perl, so + would be the equivalent in Python, yes. 

-Jay



More information about the Python-list mailing list