Add persistent hints
[p5sagit/Eval-WithLexicals.git] / lib / Eval / WithLexicals.pm
1 package Eval::WithLexicals;
2
3 use Moo;
4
5 our $VERSION = '1.001000'; # 1.1.0
6 $VERSION = eval $VERSION;
7
8 with 'Eval::WithLexicals::Role::Eval';
9 with 'Eval::WithLexicals::Role::PreludeEachTime';
10
11 =head1 NAME
12
13 Eval::WithLexicals - pure perl eval with persistent lexical variables
14
15 =head1 SYNOPSIS
16
17   # file: bin/tinyrepl
18
19   #!/usr/bin/env perl
20
21   use strictures 1;
22   use Eval::WithLexicals;
23   use Term::ReadLine;
24   use Data::Dumper;
25
26   $SIG{INT} = sub { warn "SIGINT\n" };
27
28   { package Data::Dumper; no strict 'vars';
29     $Terse = $Indent = $Useqq = $Deparse = $Sortkeys = 1;
30     $Quotekeys = 0;
31   }
32
33   my $eval = Eval::WithLexicals->new;
34   my $read = Term::ReadLine->new('Perl REPL');
35   while (1) {
36     my $line = $read->readline('re.pl$ ');
37     exit unless defined $line;
38     my @ret; eval {
39       local $SIG{INT} = sub { die "Caught SIGINT" };
40       @ret = $eval->eval($line); 1;
41     } or @ret = ("Error!", $@);
42     print Dumper @ret;
43   }
44
45   # shell session:
46
47   $ perl -Ilib bin/tinyrepl 
48   re.pl$ my $x = 0;
49   0
50   re.pl$ ++$x;
51   1
52   re.pl$ $x + 3;
53   4
54   re.pl$ ^D
55   $
56
57 =head1 METHODS
58
59 =head2 new
60
61   my $eval = Eval::WithLexicals->new(
62     lexicals => { '$x' => \1 },      # default {}
63     in_package => 'PackageToEvalIn', # default Eval::WithLexicals::Scratchpad
64     context => 'scalar',             # default 'list'
65     prelude => 'use warnings',       # default 'use strictures 1'
66   );
67
68 =head2 eval
69
70   my @return_value = $eval->eval($code_to_eval);
71
72 =head2 lexicals
73
74   my $current_lexicals = $eval->lexicals;
75
76   $eval->lexicals(\%new_lexicals);
77
78 =head2 in_package
79
80   my $current_package = $eval->in_package;
81
82   $eval->in_package($new_package);
83
84 =head2 context
85
86   my $current_context = $eval->context;
87
88   $eval->context($new_context); # 'list', 'scalar' or 'void'
89
90 =head2 prelude
91
92 Code to run before evaling code. Loads L<strictures> by default.
93
94   my $current_prelude = $eval->prelude;
95
96   $eval->prelude(q{use warnings}); # only warnings, not strict.
97
98 =head1 AUTHOR
99
100 Matt S. Trout <mst@shadowcat.co.uk>
101
102 =head1 CONTRIBUTORS
103
104 David Leadbeater <dgl@dgl.cx>
105
106 =head1 COPYRIGHT
107
108 Copyright (c) 2010 the Eval::WithLexicals L</AUTHOR> and L</CONTRIBUTORS>
109 as listed above.
110
111 =head1 LICENSE
112
113 This library is free software and may be distributed under the same terms
114 as perl itself.
115
116 =cut
117
118 1;