Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Recover a variable from a function

by Ovid (Cardinal)
on May 19, 2016 at 10:32 UTC ( #1163461=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1163461]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2020-10-29 11:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (270 votes). Check out past polls.

    Notices?