# set TEST flag before compiling tested module use constant 'PKG::TEST' => 1; # ### here normally use PKG { package PKG; use strict; use warnings; use Data::Dump qw/pp dd/; use v5.16; sub create_output { my $count =shift; my $string; my $fh; my %hash; # create (mildly) complex demo HoA $hash{$_} = [reverse 1.. $count--] for "a".."f"; # memorize datastructure when testing $PKG::TEST_result = \%hash if TEST; my $target = "c:/tmp/output.txt"; # redirect filehande to string when testing $target = \$PKG::TEST_content if TEST; open $fh, '>', $target; # Output to "file" print $fh pp \%hash; } } # ### my tests package main; use B::Deparse; use Data::Dump qw/pp dd/; # prove that TEST code disappears unless TEST is true print B::Deparse->new->coderef2text(\&PKG::create_output); PKG::create_output(5); if ( PKG::TEST ) { use Test::More; my $expected ={ a => [5, 4, 3, 2, 1], b => [4, 3, 2, 1], c => [3, 2, 1], d => [2, 1], e => [1], f => [], }; is_deeply( $PKG::TEST_result, $expected, "internal result" ); my $expected_str = pp $expected; is( $PKG::TEST_content, $expected_str, "file output" ); done_testing(); }