1

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.
  • 1
    Variable declared with [my](http://p3rl.org/my) isn't global. – choroba Sep 08 '19 at 18:31
  • (SMH) Thanks! I thought It was something stupid on my part. – Rich Farmbrough Sep 08 '19 at 18:41
  • in general, you should not have require_ok and use_ok in the same test as tests of the code those load, since if the require fails that will cause the later tests to not actually be testing what they should and fail – ysth Sep 08 '19 at 18:48

1 Answers1

1

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'};
}