Variable Declarations in Python and Perl

Consider the following program in a file named

if (0) { print $abc }
if (1) { print $abc }

When we execute this program as shown below, the program executes fine but we do not get any output (actually, it prints an empty string). Perl does not complain that the variable $abc is not defined.

$ perl

But it does complain when we execute as shown below.

$ perl -Mstrict
Global symbol "$abc" requires explicit package name at line 1.
Global symbol "$abc" requires explicit package name at line 2.

When the pragma strict is enabled, the compiler mandates the variable declaration before its usage.

Let us see how it works in Python.

$ python
Python 2.7.5+ (default, Sep 19 2013, 13:49:51) 
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if 0: print abc
>>> if 1: print abc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined

Python complains only for the 2nd if statement but not the 1st one.

Let me try to put what is happening in my own words …

Perl: When the pragma is used, we get additional help from the compiler or it just tries to execute whatever is given (Undeclared variables can act as the number zero or an empty string, etc. and it depends on the context. Context in Perl can be easily understood but difficult to master)

Python: I haven’t come across any such pragma (but tools like py_checker or pep8 would help, not tried). If you think that the code will get executed, make sure that the variables used are written (assigned some value) at least once before reading from them.

Learning: If you want a quick dirty command line or a neat perfect program, Perl offers you both (with just a pragma). Python couldn’t be relied or used the same way. Even a typo error would go unnoticed easily and it may crash at anytime (Well, this is my opinion before using py_checker or pep8 tools).

Happy Weird Programming!

P.S: I wanted to write at least one blog this month and at the very last moment, I am posting it.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s