入力文字列の履歴を保存
Term::ReadLineモジュールを使うと入力文字列の履歴を保存して、カーソルの上下で過去に入力した文字列を簡単に呼び出せるようにできます。
ESCキーで入力途中の文字列をクリアするのもできるようになります。
use strict;
use warnings;
use Term::ReadLine;
my $prompt = "計算式:";
my $term = new Term::ReadLine('my calc');
my $out = $term->OUT || \*STDOUT;
while (defined (my $in = $term->readline($prompt))) {
my $result = eval($in);
if ($@) {
print $out $@;
next;
}
$term->addhistory($in);
print $out $result, "\n";
}
use strict;
use warnings;
use Net::Amazon;
use Term::ReadLine;
use Encode;
# 環境に合わせて修正する
my $Code = 'cp932'; # 文字コードの指定
my $amazon_token = '取得したSubscription ID';
my $Amazon = Net::Amazon->new(
token => $amazon_token,
max_pages => 1,
locale => 'jp',
);
my $prompt = "\n? ";
my $term = new Term::ReadLine('my shell');
my $out = $term->OUT || \*STDOUT;
my $process = {
b => \&amazon_book_search,
h => \&help,
o => \&os_command,
p => \&perl_statement,
};
while (defined (my $in = $term->readline($prompt))) {
my ($command, @options) = split /\s/, $in;
next if $in =~ m/^\s*$/;
last if $in =~ m/^q/i;
$term->addhistory($in);
my $result = '';
if (exists $process->{$command}) {
$result = $process->{$command}->(@options);
} else {
$result = help();
}
print $out $result;
}
sub amazon_book_search {
my @param = @_;
my $res = $Amazon->search(
keyword => Encode::encode(
'utf8',
Encode::decode(
$Code,
join(" ", @param)
)
),
mode => 'books'
);
my $out = '';
foreach my $item ($res->properties) {
$out .= sprintf "%s %s\n",
$item->Asin(),
Encode::encode($Code, $item->Title());
}
return $out;
}
sub help {
return <<EOF;
b KEYWORD: search amazon books
h : display help
o COMMAND: execute os command
p STRING : evalute perl statement
q : quit
EOF
}
sub os_command {
my @command = @_;
system @command;
return '';
}
sub perl_statement {
my @command = @_;
my $ret = eval(join " ", @_);
return $@ ? $@
: defined $ret ? $ret."\n"
: '';
}
関連項目
・一文字入力待ち・Yes/No確認プロンプト
