Ian Fiddes
Ian Fiddes

Reputation: 3011

Translating perl to python - What does this line do (class variable confusion)

$self->{DES} ->{$id} = join("\t",@tmp[0 ..7]);

This line is part of a function inside of a perl class whose constructor is

sub new {
    my $class=shift;
    my $self ={};
    bless($self,$class);
    return $self;
}

The way I interpret it is that we are storing the id lines as a class variable DES which is a hash whose members are $id:. Is this correct?

I also would like some clarification about the =~ operator (which seems to always precede a regular expression). As far as I can tell it is basically just the same as in python doing re.X where X depends on the flag after the regular expression in perl (such as i). Is this correct?

Upvotes: 3

Views: 350

Answers (1)

user4815162342
user4815162342

Reputation: 155156

Your interpretation is correct. Perl will automatically create hashes-inside-hashes, sort of like Python's defaultdict subclassed to create more defaultdicts. Using regular dict and idiomatic Python, the equivalent assignment would translate as:

def __init__(self, ...):
    self.DES = {}

def foo(self, ...):
    self.DES[id_] = "\t".join(tmp[:7])

The quoted new sub is what Python would do in stock __new__:

def __new__(cls):
    self = object.__new__(cls)
    return self

bless is similar to assigning to self.__class__, except you don't need to do it in Python because object.__new__ already creates an object of the correct class. The object is first created as a hash (dict) because in Perl most class objects inherit from hash - unlike Python, where object will typically contain a dict rather than inherit from it.

The =~ operator is equivalent to calling pattern.search on an automagically compiled regular expression pattern. You get the re.X syntax only if the pattern ends with /x. Other options for patterns can be found in the copious perlre man page.

Upvotes: 7

Related Questions