Reputation: 2148
I am writing a test to test a function I have written in my utilities module. Since this function gets called multiple times, I created a module level array to cache the values in:
package MyPackage;
our @array;
sub func1 {
if (@array) {
return @array;
#continue with the rest of the code.
}
in my test, I am testing this function multiple times. However, my wish to avoid long and repeated computation has bitten me in testing!
How can I clear (undef) the array for each test?
In my test, I am doing a
BEGIN {
use_ok('MyPackage');
}
in each test function, I tried calling
undef @array;
and
undef @MyPackage::array;
and
@myPackage::array = ();
I have a print statement in my module function right after the early return (if @array), and it only prints for the first test function, so I know that the array does not get undef.
Thanks!
Upvotes: 0
Views: 142
Reputation: 3837
Your code has plenty of issues which go well beyond your question, so I'm going to detail that here (codereview.stackexchange.com would be a more appropriate place) but this is an approach to solve your particular problem:
package Foo;
my @private = ();
sub func1 {
if ( @private ) {
return @private;
}
}
sub clear {
@private = ();
}
1;
Then:
use Foo;
my @stuff = Foo::func1();
Foo::clear();
# Note: @stuff still has the old contents of the private array
For a clean separation of concern, don't ever access private variables from another package. Add functions or methods to interact with the private data instead.
Also, keep in mind that even when you call the ::clear() function, it won't empty the variable you assigned its contents to. You made a shallow copy of the data, which won't change. If you need that data to change as well you need to stop copying it and work with references instead:
sub func2 {
if ( @private ) {
return \@private;
}
}
...
my $ref = Foo::func2();
foreach ( @$ref ) {
print "value: $_\n";
}
Upvotes: 1