http://qs321.pair.com?node_id=1163461


in reply to Recover a variable from a function

It looks like you're using Test::Class. That module is specifically designed to handle situations like this. In particular, every method is called with an invocant which in this case is a blessed, empty hashref. You're allowed (even encouraged!) to shove things in that hashref. For test classes, I like to call my invocant $test instead of the standard $self.

sub Start_timer : Test(startup) { my $test = shift; my $start = time(); cprint "#\x037Started at ", (strftime '%A %d %B %Y %H:%M:%S',localti +me($start)), "\x030\n"; $test->{start} = $start; } sub End_timer : Test(shutdown) { my $test = shift; my $start = $test->{start}; my $end = time; cprint "#\x037Ended at ", (strftime '%A %d %B %Y %H:%M:%S', localtim +e($end)),"\x030\n"; cprintf "#\x035 Total run time=>", $end-$start, " seconds\n"; cprintf ("%02d:%02d:%02d\x030\n",(gmtime($end-$start))[2,1,0]); }

However, this is a practice I discourage. First, it's easy to write something like $test->{strat}; and wonder why you didn't get a value. Second, encouraging people to reach inside of objects like that is generally a bad idea.

Another solution would be to look at Test::Class::Moose and use proper attributes.

has 'start' => ( is => 'ro', isa => 'Int', default => sub { return time }, ); sub test_startup { my $test = shift; my $start = $test->start; cprint "#\x037Started at ", (strftime '%A %d %B %Y %H:%M:%S',localti +me($start)), "\x030\n"; } sub test_shutdown { my $test = shift; my $start = $test->start; my $end = time; cprint "#\x037Ended at ", (strftime '%A %d %B %Y %H:%M:%S', localtim +e($end)),"\x030\n"; cprintf "#\x035 Total run time=>", $end-$start, " seconds\n"; cprintf ("%02d:%02d:%02d\x030\n",(gmtime($end-$start))[2,1,0]); }

Also, it's a bit out of date, but you might want to read my Test::Class tutorial. It's in five parts, but it's worth the effort.

Replies are listed 'Best First'.
Re^2: Recover a variable from a function
by Chaoui05 (Scribe) on May 19, 2016 at 10:43 UTC
    Thanks for the comment. yes , in fact , Test::Class seems to allow that. I used native Perl code to do differently and because it was the first thing i thought. But i retain this approach.