Friday, June 10, 2011

Perl dualvar is useful, after all

For many years I had been intrigued by Scalar::Util::dualvar : why would one store both a number and a string within the same variable ?

Yesterday I finally found a situation where dualvar was just the perfect answer.I was doing some refactoring in DBIx::DataModel::Statement : each object from this class has a status, that goes through steps "new", "sqlized", "prepared", "executed". Originally his had been coded with plain strings; but the problem with strings is that they are not ordered, so I was considering a change to something like

use constant {NEW => 1, SQLIZED => 2, PREPARED => 3, EXECUTED => 4};

However such codes are not user-friendly, so when generating error messages I would need to translate them back into strings. Moreover, that change was not backwards compatible. So dualvar came to the rescue :

use constant {
NEW => dualvar(1, "new"),
SQLIZED => dualvar(2, "sqlized"),
PREPARED => dualvar(3, "prepared"),
EXECUTED => dualvar(4, "executed"),
};

Now I can write things like

$status >= PREPARED
or die "can't do that operation when in state $status";