Search code examples
perlterminalprompt

How can I provide an editable default value when prompting for user input?


In a Perl script, I want to prompt the user for input and offer him an editable default value. So far I have this:

#!/usr/bin/perl

print "what's your name? [John Doe]: ";
$name = <STDIN>;
chomp $name;
if (!$name)
{
    $name = "John Doe";
}
print "hello $name.\n";

What I'm looking for is a solution where I can have "John Doe" on STDIN already before the user starts typing. So it's practically an editable default input. E.g. the user could press backspace 3x and then type "Wayne" to get "John Wayne" rather than typing the whole string "John Wayne" from beginning on. I tried to print to STDIN, but that didn't work.


Solution

  • You by definition cannot write to stdin. You’re going to have to use something like Term::ReadLine::Gnu.

    The feature you are looking for is called PREPUT, it is the second argument to the readline function.