File: History.pm

package info (click to toggle)
libdevel-repl-perl 1.002001-2
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 256 kB
  • ctags: 185
  • sloc: perl: 2,323; makefile: 47
file content (52 lines) | stat: -rw-r--r-- 1,106 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package Devel::REPL::Plugin::History;

use Moose::Role;
use namespace::clean -except => [ 'meta' ];

has 'history' => (
  isa => 'ArrayRef', is => 'rw', required => 1, lazy => 1,
  default => sub { [] }
);

sub push_history {
  my ($self, $line) = @_;
  push(@{$self->history}, $line);
}

around 'read' => sub {
  my $orig = shift;
  my ($self, @args) = @_;
  my $line = $self->$orig(@args);
  if (defined $line) {
    if ($line =~ m/^!(.*)$/) {
      my $call = $1;
      $line = $self->history_call($call);
      if (defined $line) {
        $self->print($line."\n");
      } else {
        return "'Unable to find ${call} in history'";
      }
    }
    if ($line =~ m/\S/) {
      $self->push_history($line);
    }
  }
  return $line;
};

sub history_call {
  my ($self, $call) = @_;
  if ($call =~ m/^(-?\d+)$/) { # handle !1 or !-1
    my $idx = $1;
    $idx-- if ($idx > 0); # !1 gets history element 0
    my $line = $self->history->[$idx];
    return $line;
  }
  my $re = qr/^\Q${call}\E/;
  foreach my $line (reverse @{$self->history}) {
    return $line if ($line =~ $re);
  }
  return;
};

1;