1Eval::Context(3)      User Contributed Perl Documentation     Eval::Context(3)
2
3
4

NAME

6        Eval::Context - Evalute perl code in context wraper
7

SYNOPSIS

9               use Eval::Context ;
10
11               my $context = new Eval::Context(PRE_CODE => "use strict;\nuse warnings;\n") ;
12
13               # code will be evaluated with strict and warnings loaded in the context.
14
15               $context->eval(CODE => 'print "evaluated in an Eval::Context!" ;') ;
16               $context->eval(CODE_FROM_FILE => 'file.pl') ;
17

DESCRIPTION

19       This module define a subroutine that let you evaluate Perl code in a
20       specific context. The code can be passed directly as a string or as a
21       file name to read from. It also provides some subroutines to let you
22       define and optionally share variables and subroutines between your code
23       and the code you wish to evaluate. Finally there is some support for
24       running your code in a safe compartment.
25

Don't play with fire!

27       Don't start using this module, or any other module, thinking it will
28       let you take code from anywhere and be safe. Read perlsec, Safe,
29       Opcode, Taint and other security related documents. Control your input.
30

SUBROUTINES/METHODS

32       Subroutines that are not part of the public interface are marked with
33       [p].
34
35   new(@named_arguments)
36       Create an Eval::Context object.  The object is used as a repository of
37       "default" values for your code evaluations.  The context can be used
38       many times. The values can be temporarily overridden during the "eval"
39       call.
40
41         my $context = new Eval::Context() ; # default context
42
43         my $context = new Eval::Context
44                       (
45                       NAME              => 'libraries evaluation context',
46                       PACKAGE           => 'libraries',
47                       SAFE              => {...} ;
48
49                       PRE_CODE          => "use strict ;\n"
50                       POST_CODE         => sub{},
51                       PERL_EVAL_CONTEXT => undef,
52
53                       INSTALL_SUBS      => {...},
54                       INSTALL_VARIABLES => [...],
55                       EVAL_SIDE_PERSISTENT_VARIABLES => {...},
56
57                       INTERACTION => {...},
58                       DISPLAY_SOURCE_IN_CONTEXT => 1, #useful when debuging
59                       ) ;
60
61       ARGUMENTS
62
63       • @named_arguments - setup data for the object
64
65         All the arguments optional. The argument passed to "new" can also be
66         passed to "eval". All arguments are named.
67
68         •   NAME - use when displaying information about the object.
69
70             Set automatically to 'Anonymous' if not set. The name will also
71             be reported by perl if an error occurs during your code
72             evaluation.
73
74         •   PACKAGE - the package the code passed to "eval" will evaluated be
75             in.
76
77             If not set, a unique package name is generated and used for every
78             "eval" call.
79
80         •   REMOVE_PACKAGE_AFTER_EVAL - When set the content of the package
81             after evaluation will be erase
82
83             The default behavior is to remove all data from after the call to
84             "eval".
85
86         •   PRE_CODE - code prepended to the code passed to eval
87
88         •   POST_CODE - code appended to the code passed to eval
89
90         •   PERL_EVAL_CONTEXT - the context to eval code in (void, scalar,
91             list).
92
93             This option Works as  "wantarray" in perlfunc. It will override
94             the context in which "eval" is called.
95
96         •   INSTALL_SUBS - subs that will be available in the eval.
97
98             A hash where the keys are a function names and the values a code
99             references.
100
101         •   SAFE
102
103             This argument must be a hash reference. if the hash is empty, a
104             default safe compartment will be used.  Read Safe documentation
105             for more information.
106
107                     SAFE => {} # default safe environment
108
109             You can have a finer control over the safe compartment
110             Eval::Context that will be used.
111
112                     my $compartment = new Safe('ABC') ;
113
114                     my $context = new Eval::Context
115                             (
116                             SAFE => # controlling the safe environment
117                                     {
118                                     PACKAGE     => 'ABC',
119                                     PRE_CODE    => "use my module ;\n" # code we consider safe
120                                     USE_STRICT  => 0,                # set to 1 by default
121                                     COMPARTMENT => $compartment ,   # use default if not passed
122                                     } ,
123                             }
124
125                     $context->eval(CODE => .....) ;
126
127             •   COMPARTMENT - a Safe object, you create, that will be used by
128                 Eval::Context
129
130             •   USE_STRICT - Controls if strict is used in the Safe
131                 compartment
132
133                 The default is to use strict. Note that "Safe" in perldoc
134                 default is to NOT use strict (undocumented).
135
136             •   PRE_CODE - safe code you want to evaluate in the same context
137                 as the unsafe code
138
139                 This let you, for example, use certain modules which provide
140                 subroutines to be used in the evaluated code. The default
141                 compartment is quite restrictive and you can't even use
142                 strict in it without tuning the safe compartment.
143
144             A few remarks:
145
146             - See <http://rt.cpan.org/Ticket/Display.html?id=31090> on RT
147
148             - Pass the same package name to your safe compartment and to
149             Eval::Context.
150
151             - If you really want to be on the safe side, control your input.
152             When you use a module, are you sure the module hasn't been fiddle
153             with?
154
155             - Leave strict on. Even for trivial code.
156
157         •   INSTALL_VARIABLES - "Give me sugar baby" Ash.
158
159             Eval::Context has mechanisms you can use to set and share
160             variables with the code you will evaluate. There are two sides in
161             an Eval::Context. The caller-side, the side where the calls to
162             "eval" are made and the eval-side, the side where the code to be
163             evaluated is run.
164
165             •   How should you get values back from the eval-side
166
167                 Although you can use the mechanisms below to get values from
168                 the eval-side, the cleanest way is to get the results
169                 directly from the "eval" call.
170
171                         my $context = new Eval::Context() ;
172
173                         my ($scalr_new_value, $a_string) =
174                                 $context->eval
175                                         (
176                                         INSTALL_VARIABLES =>[[ '$scalar'  => 42]] ,
177                                         CODE => "\$scalar++ ;\n (\$scalar, 'a string') ;",
178                                         ) ;
179
180             •   initializing variables on the eval side
181
182                 You can pass INSTALL_VARIABLES to "new" or "eval". You can
183                 initialize different variables for each run of "eval".
184
185                         my $context = new Eval::Context
186                                 (
187                                 INSTALL_VARIABLES =>
188                                         [
189                                         # variables on eval-side    #initialization source
190                                         [ '$data'                => 42],
191                                         [ '$scalar'              => $scalar_caller_side ],
192                                         [ '%hash'                => \%hash_caller_side ]
193                                         [ '$hash'                => \%hash_caller_side ],
194                                         [ '$object'              => $object ],
195                                         ] ,
196                                 ) ;
197
198                 The variables will be my variables on the eval-side.
199
200                 You can declare variables of any of the base types supported
201                 by perl. The initialization data , on the caller-side, is
202                 serialized and deserialized to make the values available on
203                 the eval-side. Modifying the variables on the eval-side does
204                 not modify the variables on the caller-side. The
205                 initialization data can be scalars or references and even my
206                 variables.
207
208             •   Persistent variables
209
210                 When evaluating code many times in the same context, you may
211                 wish to have variables persist between evaluations.
212                 Eval::Context allows you to declare, define and control such
213                 state variables.
214
215                 This mechanism lets you control which variables are
216                 persistent. Access to the persistent variables is controlled
217                 per "eval" run. Persistent variables are my variables on the
218                 eval-side. Modifying the variables on the eval-side does not
219                 modify the variables on the caller-side.
220
221                 Define persistent variables:
222
223                         # note: creating persistent variables in 'new' makes little sense as
224                         # it will force those values in the persistent variables for every run.
225                         # This may or may not be what you want.
226
227                         my $context = new Eval::Context() ;
228
229                         $context->eval
230                                 (
231                                 INSTALL_VARIABLES =>
232                                         [
233                                         [ '$scalar'  => 42                 => $Eval::Context::PERSISTENT ] ,
234
235                                         # make %hash and $hash available on the eval-side. both are
236                                         # initialized from the same caller-side hash
237                                         [ '%hash'    => \%hash_caller_side => $Eval::Context::PERSISTENT ] ,
238                                         [ '$hash'    => \%hash_caller_side => $Eval::Context::PERSISTENT ] ,
239                                         ],
240                                 CODE => '$scalar++',
241                                 ) ;
242
243                 Later, use the persistent value:
244
245                         $context->eval
246                                 (
247                                 INSTALL_VARIABLES =>
248                                         [
249                                         [ '$scalar'  => $Eval::Context::USE => $Eval::Context::PERSISTENT ] ,
250                                         # here you decided %hash and $hash shouldn't be available on the eval-side
251                                         ],
252
253                                 CODE => '$scalar',
254                                 ) ;
255
256                 $Eval::Context::USE means "make the persistent variable and
257                 it's value available on the eval-side".  Any other value will
258                 reinitialize the persistent variable. See also
259                 REMOVE_PERSISTENT in "eval".
260
261             •   Manually synchronizing caller-side data with persistent eval-
262                 side data
263
264                 Although the first intent of persistent variables is to be
265                 used as state variables on the eval-side, you can get
266                 persistent variables values on the caller-side. To change the
267                 value of an eval-side persistent variable, simply
268                 reinitialize it with INSTALL_VARIABLES next time you call
269                 "eval".
270
271                         my $context = new Eval::Context
272                                         (
273                                         INSTALL_VARIABLES =>
274                                                 [
275                                                 ['%hash' => \%hash_caller_side => $Eval::Context::PERSISTENT]
276                                                 ] ,
277                                         ) ;
278
279                         $context->Eval(CODE => '$hash{A}++ ;') ;
280
281                         # throws exception if you request a non existing variable
282                         my %hash_after_eval = $context->GetPersistantVariables('%hash') ;
283
284             •   Getting the list of all the PERSISTENT variables
285
286                         my @persistent_variable_names = $context->GetPersistantVariablesNames() ;
287
288             •   Creating persistent variables on the eval-side
289
290                 The mechanism above gave you fine control over persistent
291                 variables on the eval-side.  The negative side is that only
292                 the variables you made persistent exist on the eval-side.
293                 Eval::Context has another mechanism that allows the eval-side
294                 to store variables between evaluations without the caller-
295                 side declaration of the variables.
296
297                 To allow the eval-side to store any variable, add this to you
298                 "new" call.
299
300                         my $context = new Eval::Context
301                                 (
302                                 PACKAGE => 'my_package',
303
304                                 EVAL_SIDE_PERSISTENT_VARIABLES =>
305                                         {
306                                         SAVE => { NAME => 'SavePersistent', VALIDATOR => sub{} },
307                                         GET  => { NAME => 'GetPersistent',  VALIDATOR => sub{} },
308                                         },
309                                 ) ;
310
311                 The eval-side can now store variables between calls to "eval"
312
313                         SavePersistent('name', $value) ;
314
315                 later in another call to "eval":
316
317                         my $variable = GetPersistent('name') ;
318
319                 By fine tuning EVAL_SIDE_PERSISTENT_VARIABLES you can control
320                 what variables are stored by the eval-side. This should
321                 seldom be used and only to help those storing data from the
322                 eval-side.
323
324                 You may have notices in the code above that a package name
325                 was passed as argument to "new". This is very important as
326                 the package names that are automatically generated differ for
327                 each "eval" call. If you want to run all you eval-side code
328                 in different packages (Eval::Context default behavior), you
329                 must tell Eval::Context where to store the eval-side values.
330                 This is done by setting CATEGORY
331
332                 The validator sub can verify if the value to be stored are
333                 valid, E.G.: variable name, variable value is within range,
334                 ...
335
336                 Here is an example of code run in different packages but can
337                 share variables. Only variables which names start with A are
338                 valid.
339
340                         new Eval::Context
341                                 (
342                                 EVAL_SIDE_PERSISTENT_VARIABLES =>
343                                         {
344                                         CATEGORY => 'TEST',
345                                         SAVE =>
346                                                 {
347                                                 NAME => 'SavePersistent',
348                                                 VALIDATOR => sub
349                                                         {
350                                                         my ($self, $name, $value, $package) = @_ ;
351                                                         $self->{INTERACTION}{DIE}->
352                                                                 (
353                                                                 $self,
354                                                                 "SavePersistent: name '$name' doesn't start with A!"
355                                                                 )  unless $name =~ /^A/ ;
356                                                         },
357                                                 },
358
359                                         GET => {NAME => 'GetPersistent',VALIDATOR => sub {}},
360                                         },
361                                 ) ;
362
363                         $context->eval(CODE => 'SavePersistent('A_variable', 123) ;') ;
364
365                 later:
366
367                         $context->eval(CODE => 'GetPersistent('A_variable') ;') ;
368
369             •   Shared variables
370
371                 You can also share references between the caller-side and the
372                 eval-side.
373
374                         my $context =
375                                 new Eval::Context
376                                         (
377                                         INSTALL_VARIABLES =>
378                                                 [
379                                                 # reference to reference only
380                                                 [ '$scalar' => \$scalar           => $Eval::Context::SHARED ],
381                                                 [ '$hash'   => \%hash_caller_side => $Eval::Context::SHARED ],
382                                                 [ '$object' => $object            => $Eval::Context::SHARED ],
383                                                 ] ,
384                                         ) ;
385
386                 Modification of the variables on the eval-side will modify
387                 the variable on the caller-side.  There are but a few reasons
388                 to share references. Note that you can share references to my
389                 variables.
390
391         •   INTERACTION
392
393             Lets you define subs used to interact with the user.
394
395                     INTERACTION      =>
396                             {
397                             INFO     => \&sub,
398                             WARN     => \&sub,
399                             DIE      => \&sub,
400                             EVAL_DIE => \&sub,
401                             }
402
403             INFO - defaults to CORE::print
404                   This sub will be used when displaying information.
405
406             WARN - defaults to Carp::carp
407                   This sub will be used when a warning is displayed.
408
409             DIE - defaults to Carp::confess
410                   Used when an error occurs.
411
412             EVAL_DIE - defaults to Carp::confess, with a dump of the code to
413             be evaluated
414                   Used when an error occurs during code evaluation.
415
416         •   FILE - the file where the object has been created.
417
418             This is practical if you want to wrap the object.
419
420             FILE and LINE will be set automatically if not set.
421
422         •   LINE - the line where the object has been created. Set
423             automatically if not set.
424
425         •   DISPLAY_SOURCE_IN_CONTEXT - if set, the code to evaluated will be
426             displayed before evaluation
427
428       Return
429
430       • an Eval::Context object.
431
432   [p] Setup
433       Helper sub called by new.
434
435   [p] CheckOptionNames
436       Verifies the named options passed as arguments with a list of valid
437       options. Calls {INTERACTION}{DIE} in case of error.
438
439   [p] SetInteractionDefault
440       Sets {INTERACTION} fields that are not set by the user.
441
442   [p] CanonizeName
443       Transform a string into a a string with can be used as a package name
444       or file name usable within perl code.
445
446   eval(@named_arguments)
447       Evaluates Perl code, passed as a string or read from a file, in the
448       context.
449
450               my $context = new Eval::Context(PRE_CODE => "use strict;\nuse warnings;\n") ;
451
452               $context->eval(CODE => 'print "evaluated in an Eval::Context!";') ;
453               $context->eval(CODE_FROM_FILE => 'file.pl') ;
454
455       Call context
456
457       Evaluation context of the code (void, scalar, list) is the same as the
458       context this subroutine was called in or in the context defined by
459       PERL_EVAL_CONTEXT if that option is present.
460
461       Arguments
462
463       NOTE: You can override any argument passed to "new". The override is
464       temporary during the duration of this call.
465
466       • @named_arguments - Any of "new" options plus the following.
467
468         •   CODE - a string containing perl code (valid code or an exception
469             is raised)
470
471         •   CODE_FROM_FILE - a file containing  perl code
472
473         •   REMOVE_PERSISTENT
474
475             A list of regex used to match the persistent variable names to be
476             removed, persistent variable removal is done before any variable
477             installation is done
478
479         •   FILE and LINE - will be used in the evaluated code 'file_name'
480             set to the caller's file and line by default
481
482         NOTE: CODE or CODE_FROM_FILE is mandatory.
483
484       Return
485
486       • What the code to be evaluated returns
487
488   [p] VerifyAndCompleteOptions
489       Helper sub for "eval".
490
491   [p] EvalCleanup
492       Handles the package cleanup or persistent variables cleanup after a
493       call to "eval".
494
495   [p] GetPackageName
496       Returns a canonized package name. the name is either passed as argument
497       from the caller or a temporary package name.
498
499   [p] EvalSetup
500       Handles the setup of the context before eval-side code is evaluated.
501       Sets the variables and the shared subroutines.
502
503   [p] VerifyCodeInput
504       Verify that CODE or CODE_FROM_FILE are properly set.
505
506   [p] RemovePersistent
507       Handles the removal of persistent variables.
508
509   [p] GetCallContextWrapper
510       Generates perl code to wrap the code to be evaluated in the right
511       calling context.
512
513   [p] SetupSafeCompartment
514       If running in safe mode, setup a safe compartment from the argument,
515       otherwise defines the evaluation package.
516
517   [p] GetInstalledVariablesCode
518       Generates variables on the eval-side from the INSTALL_VARIABLES
519       definitions.  Dispatches the generation to specialize subroutines.
520
521   [p] GetPersistentVariablesSetFromCaller
522       Generates code to make persistent variables, defined on the caller-side
523       available on the eval-side.
524
525   [p] GetSharedVariablesSetFromCaller
526       Handles the mechanism used to share variables (references) between the
527       caller-side and the eval-side.
528
529       Shared variables must be defined and references. If the shared variable
530       is undef, the variable that was previously shared, under the passed
531       name, is used if it exists or an exception is raised.
532
533       Also check that variables are not PERSISTENT and SHARED.
534
535   [p] GetVariablesSetFromCaller
536       Generates code that creates local variables on the eval-side
537
538   GetPersistentVariableNames()
539       Arguments - none
540
541       Returns - the list of existing persistent variables names
542
543               my @persistent_variable_names = $context->GetPersistantVariablesNames() ;
544
545   GetPersistantVariables(@variable_names)
546       Arguments
547
548       • @variable_names - list of variable names to retrieve
549
550       Returns - list of values corresponding to the input names
551
552       This subroutine will return whatever the caller-site set or the eval-
553       side modified. Thus if you created a %hash persistent variable, a hash
554       (not a hash reference) will be returned.
555
556       If you request multiple values, list flattening will be in effect. Be
557       careful.
558
559               my $context = new Eval::Context
560                               (
561                               INSTALL_VARIABLES =>
562                                       [
563                                       ['%hash' => \%hash_caller_side => $Eval::Context::PERSISTENT]
564                                       ] ,
565                               ) ;
566
567               $context->Eval(CODE => '$hash{A}++ ;') ;
568
569               # may throw exception
570               my %hash_after_eval = $context->GetPersistantVariables('%hash') ;
571
572   [p] SetEvalSidePersistenceHandlers
573       Set the code needed to handle eval-side persistent variables.
574
575   [p] RemoveEvalSidePersistenceHandlers
576       Removes eval-side persistent variable handlers. Used after calling
577       "eval" so the next "eval" can not access eval-side persistent variables
578       without being allowed to do so.
579

BUGS AND LIMITATIONS

581       I have reported a very strange error when Safe and Carp are used
582       together.  <http://rt.cpan.org/Ticket/Display.html?id=31090>. The error
583       can be reproduced without using Eval::Context.
584

AUTHOR

586               Khemir Nadim ibn Hamouda
587               CPAN ID: NKH
588               mailto:nadim@khemir.net
589
591       This program is free software; you can redistribute it and/or modify it
592       under the same terms as Perl itself.
593

SUPPORT

595       You can find documentation for this module with the perldoc command.
596
597           perldoc Eval::Context
598
599       You can also look for information at:
600
601       •   AnnoCPAN: Annotated CPAN documentation
602
603           <http://annocpan.org/dist/Eval-Context>
604
605       •   RT: CPAN's request tracker
606
607           Please report any bugs or feature requests to  L
608           <bug-eval-context@rt.cpan.org>.
609
610           We will be notified, and then you'll automatically be notified of
611           progress on your bug as we make changes.
612
613       •   Search CPAN
614
615           <http://search.cpan.org/dist/Eval-Context>
616
617
618
619perl v5.36.0                      2022-07-22                  Eval::Context(3)
Impressum