in reply to Recover a variable from a function

Hi Chaoui05,

One approach, which avoids directly manipulating a global, is to pass around a "context" (a term/concept commonly used e.g. in Java), basically a data structure that holds state information that would normally be stored in globals. The advantage is you can have multiple contexts at the same time, and at least in Java context objects are often thread-safe, serializable containers for what essentially are global variables. The following approach has similarities to an OO approach (you could imagine the subs in the example being methods on an object which holds the state), but the difference is that a context data structure is independent of the functions/methods that use it - it's often an object of its own (although in this example I've just used a hashref). Implementing such a "context" data structure to replace globals can be a good first step in modularizing a legacy script.

use warnings; use strict; my $ctx = {}; run($ctx); stop($ctx); stats($ctx); sub run { my ($ctx) = @_; $ctx->{start} = time; sleep 2; } sub stop { my ($ctx) = @_; $ctx->{end} = time; } sub stats { my ($ctx) = @_; $ctx->{runtime} = $ctx->{end} - $ctx->{start}; print "Start: ".gmtime($ctx->{start})." UTC\n"; print " Stop: ".gmtime($ctx->{end})." UTC\n"; print " Time: ".$ctx->{runtime}." s\n"; } __END__ Start: Thu May 19 07:29:27 2016 UTC Stop: Thu May 19 07:29:29 2016 UTC Time: 2 s

Hope this helps,
-- Hauke D

Update: Expanded description a bit.

Replies are listed 'Best First'.
Re^2: Recover a variable from a function
by Chaoui05 (Scribe) on May 19, 2016 at 07:49 UTC
    Ok i understand but it seems to be longer with your approach . Is it ?

      Hi Chaoui05,

      Yes, this approach is going to be a little more code - but only a few lines, depending on the specific case of course. However, as is often the case with such trade-offs, the little bit of time you spend writing a few more lines of code today may be much less than the time spent on debugging issues caused by misuse of global variables or the refactoring of the code as it grows more complex tomorrow.

      Hope this helps,
      -- Hauke D

        Oh yes i understand. Sometimes it's better to spend more time at the beginning.. In any case, we have different approachs in Perl