Thursday, April 19, 2007

Command interface : Tab completion in perl

For a project I'm working on just now, and because I'm very lazy, I wanted to have tab completion of the many variable commands entered. Finding a module was easy : Term::ReadLine - finding a simple example was difficult, but in the end I got it.

It is not complete by any means, but it will get you started!

use strict;
use warnings;
use Term::ReadLine;
my $term = new Term::ReadLine 'Simple Perl calc';
my $prompt = "cmd >> ";

my $attribs = $term->Attribs;
$attribs->{completion_function} = sub {
my ($text, $line, $start) = @_;
return qw(a list of candidates to complete);
};

my $OUT = $term->OUT \*STDOUT;
while ( defined ($_ = $term->readline($prompt)) ) {
my $res = eval($_);
warn $@ if $@;
print $OUT $res, "\n" unless $@;
$term->addhistory($_) if /\S/;

}

4 comments:

blackberryoctopus said...

If I paste your code directly to a script and execute the code fails with this error :

Backslash found where operator expected at ./tabComplete line 18, near "->OUT \"
(Missing operator before \?)
syntax error at ./tabComplete line 18, near "->OUT \"
Execution of ./tabComplete aborted due to compilation errors.

Simon said...

I had a quick look at this, but can't figure out what's wrong. Perhaps something has changed with the module, or the version of core perl since I used it.

If you do find a solution please post it back here!

Unknown said...

Try this:

my $OUT = $term->OUT || \*STDOUT;

That seems to work for me.

Peter B. said...

On MacOSX, I first needed to install p5-term-readline-gnu from MacPorts.

Thanks for the getting started tip!

-Peter