a87d4c7abd541f0b63d1159cba0d773933104fe3
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / DumpHistory.pm
1 use strict;
2 use warnings;
3 package Devel::REPL::Plugin::DumpHistory;
4
5 use Devel::REPL::Plugin;
6 use namespace::autoclean;
7
8 ## Seems to be a sequence issue with requires
9 # requires qw{ history }; 
10
11 around 'read' => sub {
12   my $orig = shift;
13   my ($self, @args) = @_;
14
15   my $line = $self->$orig(@args);
16   if (defined $line) {
17     if ($line =~ m/^:dump ?(.*)$/) {
18       my $file = $1;
19       $self->print_history($file);
20       return '';
21     }
22   }
23   return $line;
24 };
25
26 sub print_history {
27     my ( $self, $file ) = @_;
28
29     if ($file) {
30         open( my $fd, ">>", $file )
31             or do { warn "Couldn't open '$file': $!\n"; return; };
32         print $fd "$_\n" for ( @{ $self->history } );
33         $self->print( sprintf "Dumped %d history lines to '$file'\n",
34             scalar @{ $self->history } );
35         close $fd;
36     } else {
37         $self->print("$_\n") for ( @{ $self->history } );
38     }
39     return 1;
40 }
41
42 1;
43
44 __END__
45
46 =head1 NAME
47
48 Devel::REPL::Plugin::DumpHistory - Plugin for Devel::REPL to save or print
49 the history.
50
51 =head1 SYNOPSIS
52
53     #!/usr/bin/perl 
54
55     use lib './lib';
56     use Devel::REPL;
57
58     my $repl = Devel::REPL->new;
59     $repl->load_plugin('LexEnv');
60     $repl->load_plugin('History');
61     $repl->load_plugin('DumpHistory');
62     $repl->run;
63
64 =head1 DESCRIPTION
65
66 Plugin that adds the C<:dump> and C<:dump file_name> commands to the 
67 repl which will print the history to STDOUT or append the history to the
68 file given.
69
70 =head1 SEE ALSO
71
72 C<Devel::REPL>
73
74 =head1 AUTHOR
75
76 mgrimes, E<lt>mgrimes at cpan dot org<gt>
77
78 =head1 COPYRIGHT AND LICENSE
79
80 Copyright (C) 2007 by mgrimes
81
82 This library is free software; you can redistribute it and/or modify
83 it under the same terms as Perl itself, either Perl version 5.8.2 or,
84 at your option, any later version of Perl 5 you may have available.
85
86 =cut