Hi there
I am translating PERL code into python and i am new on both language.I have one question if we have hash key reference in PERL like this way
$a->{b}
how we can traslate it into PYTHON?
and if we have this code $a->{$b} , how we translate it into PYTHON also?
Waiting for help. Thanks
Regards
Sarfraz

Dani AI

Generated

Short answer: when the Perl arrow is dereferencing a hashref, use Python dictionaries and bracket access — but pay attention to whether the key is a literal or stored in a variable.

gave the right idea that a hashref becomes a dict; to expand: \$a->{b} (a bareword key) refers to the literal key "b", while \$a->{$b} uses the value stored in Perl variable $b. In Python the equivalents are a['b'] for the literal, and a[key] when key is a Python variable holding the lookup key (note: drop the $ in variable names).

Example patterns (Python):

# variable-key example
key = 'b'
inventory = {'b': 10}
print(inventory[key])   # uses the variable 'key' for lookup

# safely create/use nested dicts
d = {}
d.setdefault('outer', {})['inner'] = 'value'
print(d['outer']['inner'])

Practical tips when converting larger code:

  • Confirm the Perl expression is a hash lookup, not an object method. Perl uses -> for both; if it's a hashref (e.g. created with { ... } or a reference), use dicts in Python. If it was an object, convert to attribute access (obj.attr) or getattr as appropriate.
  • To check presence: Perl exists $a->{b} → Python 'b' in a. For definedness: Perl defined $a->{b} → in Python check 'b' in a and a['b'] is not None.
  • Watch key types: Perl stringifies keys; Python keys keep their type (int, tuple, etc.). Convert types deliberately when needed.
  • For nested structures, collections.defaultdict or setdefault reduce boilerplate and KeyError handling.

This should cover the two cases you asked about and help when you translate surrounding logic.

Recommended Answers

All 2 Replies

# Hashes/Arrays are known as Libraries in Python:
a = {}
a['b'] = 0
print(a)
print(a['b'])
# Hashes/Arrays are known as Libraries in Python:
a = {}
a['b'] = 0
print(a)
print(a['b'])

Thanks friend for guidance....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.