in reply to Recover a variable from a function

The simplest approach is to not use a lexical variable but a global variable:

use vars '$start'; sub Start_timer : Test(startup) { $start = time; ... }; sub End_timer : Test(shutdown) { print time - $start; ... }

If you really want to avoid global variables for things like that, you could use the state keyword and a function to read the start time:

sub get_or_init_start_time { state $start ||= time; }

You need to call this function in two places, once to initialize the $time variable and once to retrieve the value.

Replies are listed 'Best First'.
Re^2: Recover a variable from a function
by Chaoui05 (Scribe) on May 19, 2016 at 07:45 UTC
    Thanks Corion ! I have to use also global variables instead of lexical variables.
Re^2: Recover a variable from a function
by Chaoui05 (Scribe) on May 19, 2016 at 08:36 UTC
    I did that easily but it doesn't work:
    use vars '$start'; sub Start_timer : Test(startup) { my $start = time(); cprint "#\x037Started at ", (strftime '%A %d %B %Y %H:%M:%S',localti +me($start)), "\x030\n"; } sub End_timer : Test(shutdown) { print time - $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]); }
    And i have this following issue in my shell :
    ok 243 - Logout ok Use of uninitialized value $MyTest::start in subtraction (-) at MyTest +.pm line 402. 1463646157#Ended at jeudi 19 mai 2016 10:22:37 Use of uninitialized value $MyTest::start in subtraction (-) at MyTest +ingSuite.pm line 407. # Total run time=>Use of uninitialized value $MyTest::start in subtrac +tion (-) at MyTest.pm line 408. 08:22:37
        It works . Perfect . And the link is very useful. Many thanks , as usual Corion !