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.


In reply to Re: Recover a variable from a function by haukex
in thread Recover a variable from a function by Chaoui05

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.