Namespace Clobbering in Perl.

Last night, I was bitten by namespace clobbering in Perl. I am not sure if that is what it is called.

I was modifying Perl code I had written to parse log files generated by MRTG to track traffic that comes into and goes out of an interface on a device being monitored. The part of code I was tweaking depended on calculating date and time through localtime, which is a built-in function in Perl. However, instead of throwing what I was expecting it to throw, the function was displaying a bogus Array Reference. Since that part of the code worked as documented in the manual when moved into and run from a separate source file independent of the bigger piece of code I was trying to get it to coexist with, I was stumped looking for the problem for a long time.

It took me a few hours to bump into the documentation for the Time::localtime module imported early in the actual code. Apparently, importing Time::localtime was clobbering the local namespace by overriding the local localtime function. Since the module was being loaded in the actual source file and not in the smaller, test source script, the code broke when run from within the bigger source than when run from the test script. This behaviour is documented in “perldoc Time::localtime”.

Like what I usually do when I stumble on a problem that involves programming languages, I logged on #perl on A few people suggest a few alternatives. The one that worked for me involves not importing the module at all, and, instead, indirectly calling the module’s function at whatever point in code it is required. For example:

$sec = Time::localtime::localtime->sec;
my ($sec, $min, $hour, $mday, $mon, $year, undef, undef, undef) = localtime($timestamp);

The first line invokes the localtime() method defined within Time::localtime, while the following calls the built-in localtime() function.

One thought on “Namespace Clobbering in Perl.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s