Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle arrow keys in a Perl script under cygwin?

I am running Perl script under cygwin which takes input from <STDIN> and process the requests continuously.

#!/usr/bin/perl
print "Enter Input:";
while(<STDIN>) {
    print "Recieved Input: $_";
    print "Enter Input:";
}



    $perl testPerl.pl        
    Enter input:input1
    Recieved input:input1
    Enter input:inpt2
    Recieved input:input2
    Enter input:

Now, I would like the up arrow at the current prompt: "Enter input:" to take the previous inputs i.e "input2","input1"

It behaves as expected when running under windows enivronment (cmd.exe)
But the problem under cygwin is that the up arrow literally takes the cursor 1 row up i.e it takes to the line "Recieved input:input2"

Please share your thoughts on this.

like image 780
Naga Kiran Avatar asked Jan 16 '10 18:01

Naga Kiran


2 Answers

Look at the Term::Readline module. This will take over input for your program, and handles history, which is what I think you're talking about.

This would be a direct translation of your program to using Term::ReadLine:

 use Term::ReadLine;
 my $term = new Term::ReadLine 'Simple Perl calc';
 my $prompt = "Enter Input: ";
 while ( defined ($_ = $term->readline($prompt)) ) {
   print "Recieved Input:$_\n";
   $term->addhistory($_) if /\S/;
 }

like image 119
gorilla Avatar answered Oct 06 '22 00:10

gorilla


There's a big difference in the handling of the command line history between the Windows console and Unix terminals. On Windows, it's done by the console, whereas on Unix, applications are responsible for it. I don't know anything about Perl, but you'll need to use something like the readline library. This looks helpful: http://perldoc.perl.org/functions/readline.html

like image 37
ak. Avatar answered Oct 05 '22 23:10

ak.