| 1 | package App::PerlShell::LexPersist; | ||
| 2 | |||
| 3 | ######################################################## | ||
| 4 | # AUTHOR = Michael Vincent | ||
| 5 | # www.VinsWorld.com | ||
| 6 | ######################################################## | ||
| 7 | |||
| 8 | use strict; | ||
| 9 | use warnings; | ||
| 10 | |||
| 11 | use Lexical::Persistence 1.01 (); | ||
| 12 | |||
| 13 | our @ISA = qw( Lexical::Persistence ); | ||
| 14 | |||
| 15 | our $PACKAGE = undef; | ||
| 16 | |||
| 17 | sub new { | ||
| 18 | my $class = shift; | ||
| 19 | |||
| 20 | my $package = 'App::PerlShell'; | ||
| 21 | my %params; | ||
| 22 | if ( @_ == 1 ) { | ||
| 23 | ($package) = @_; | ||
| 24 | } else { | ||
| 25 | my %cfg = @_; | ||
| 26 | for ( keys(%cfg) ) { | ||
| 27 | if (/^-?package$/i) { | ||
| 28 | $package = $cfg{$_}; | ||
| 29 | delete $cfg{$_}; | ||
| 30 | } else { | ||
| 31 | $params{$_} = $cfg{$_}; | ||
| 32 | } | ||
| 33 | } | ||
| 34 | } | ||
| 35 | |||
| 36 | my $self = $class->SUPER::new(@_); | ||
| 37 | |||
| 38 | $self->{package} = $package; | ||
| 39 | # following line avoids ugly error if first command in shell is | ||
| 40 | # $var = ... without the "my" | ||
| 41 | $PACKAGE = $package; | ||
| 42 | |||
| 43 | return $self; | ||
| 44 | } | ||
| 45 | |||
| 46 | sub get_package { | ||
| 47 | $_[0]->{package}; | ||
| 48 | } | ||
| 49 | |||
| 50 | sub set_package { | ||
| 51 | $_[0]->{package} = $_[1]; | ||
| 52 | } | ||
| 53 | |||
| 54 | sub prepare { | ||
| 55 | my $self = shift; | ||
| 56 | my $code = shift; | ||
| 57 | my $package = $self->get_package; | ||
| 58 | |||
| 59 | # Put the package handling tight around the code to execute | ||
| 60 | $code = <<"END_PERL"; | ||
| 61 | package $package; | ||
| 62 | |||
| 63 | $code | ||
| 64 | |||
| 65 | BEGIN { | ||
| 66 | \$App::PerlShell::LexPersist::PACKAGE = __PACKAGE__; | ||
| 67 | } | ||
| 68 | END_PERL | ||
| 69 | |||
| 70 | # Hand off to the parent version | ||
| 71 | return $self->SUPER::prepare( $code, @_ ); | ||
| 72 | } | ||
| 73 | |||
| 74 | # Modifications to the package are tracked at compile-time | ||
| 75 | sub compile { | ||
| 76 | my $self = shift; | ||
| 77 | my $sub = $self->SUPER::compile(@_); | ||
| 78 | |||
| 79 | # Save the package state | ||
| 80 | $self->set_package($PACKAGE); | ||
| 81 | |||
| 82 | return $sub; | ||
| 83 | } | ||
| 84 | |||
| 85 | 1; | ||
| 86 | |||
| 87 | __END__ |