Variable Declarations in Python and Perl

Consider the following program in a file named var.pl

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 var.pl

But it does complain when we execute as shown below.

$ perl -Mstrict var.pl
Global symbol "$abc" requires explicit package name at no_strict.pl line 1.
Global symbol "$abc" requires explicit package name at no_strict.pl 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.

Advertisements