in reply to Context propagation into subs and evals

As far as I am aware, there are only two situations in which the context of a subroutine can affect or refer in any way to the context of its caller, viz:

  1. If the caller provides a reference to a particular value, explicitly or implicitly, then the subroutine may employ the reference, as any other piece of code equally can.
  2. Perl supports closures, which consist of CODE references as in the following one-liner example:
    sub bar { my $foo="bar"; return sub { print "foo is $foo\n"; } } my $fn = bar(); &$fn; foo is bar
    Note how the function returned by sub bar references the local variable $foo and how the value remains accessible when the main-program invokes the subroutine (“closure”...) denoted by that result.

eval has two distinct meanings:   on-the-spot evaluation of the contents of a character string, and trapping of run-time errors.   In both instances, AFAIK, they are treated as lexical blocks occurring at that point.   (In the latter case, the block would be the same even if the keyword eval did not precede it.)

Replies are listed 'Best First'.
Re^2: Context propagation into subs and evals
by LanX (Sage) on Feb 20, 2012 at 14:22 UTC
    I think you are defining the term "context" differently.

    It might be used like this when discussing variable pads and closures...(?)

    ...but that's not my point.

    Please see the definition in perlglossary to understand my interpretation:

         The surroundings, or environment.  The context given by the
         surrounding code determines what kind of data a particular
         "expression" is expected to return.  The three primary contexts are
         "list context", "scalar context", and "void context".  Scalar
         context is sometimes subdivided into "Boolean context", "numeric
         context", "string context", and "void context".  Thereís also a
         "donít care" scalar context (which is dealt with in Programming
         Perl, Third Edition, Chapter 2, "Bits and Pieces" if you care).

    UPDATE: see also wantarray

    Cheers Rolf