Search code examples
unit-testingperlglobal-variablesmodulino

Accessing a global in a perl modulino from a test


In a unit test I need to set a global variable used in a perl script that I have changed into a modulino. I'm calling subs in the modulino quite happily.

Using perl (v5.18.2) built for x86_64-linux-gnu-thread-multi, on Ubuntu.

Note the modulino is so simple it doesn't even require the "caller()" trick.

test.pl

#!/usr/bin/perl
use strict;
use warnings;

my %config =
(
    Item => 5,
);

sub return_a_value{
    return 3;
}

test1.t

#!/user/bin/perl -w
use warnings;
use strict;
use Test::More;
use lib '.';
require_ok ( 'test.pl' );

print return_a_value();

test2.t

#!/user/bin/perl -w
use warnings;
use strict;
use Test::More;
use lib '.';
require_ok ( 'test.pl' );

$config{'Item'} = 6;

test1.t displays as expected

ok 1 - require 'test.pl';
3# Tests were run but no plan was declared and done_testing() was not seen

test2.t (fails to compile)

Global symbol "%config" requires explicit package name at test.t line 8.
Execution of test.t aborted due to compilation errors.

Solution

  • As pointed out by choroba, my variables aren't global. The best solution for me, and what I should have done to start with is to add a setter sub to the modulino, something like:

    sub setItem
    {
        $config{'Item'} = shift;
        return;
    }
    

    and since I am now going to want a unit test for that, a getter is also a good idea

    sub getItem
    {
        return $config{'Item'};
    }