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 | |
by haukex (Archbishop) on May 19, 2016 at 08:22 UTC | |
by Chaoui05 (Scribe) on May 19, 2016 at 08:40 UTC | |
by haukex (Archbishop) on May 19, 2016 at 08:44 UTC | |
by Chaoui05 (Scribe) on May 20, 2016 at 07:28 UTC |