in reply to Re: restriction in input
in thread restriction in input

For example, I am getting user name from stdin. I restricted the user name must be less than 15 characters. So when user try to type 16th character, I won't allow the user to type. How can I achieve in Perl.

Replies are listed 'Best First'.
Re^3: restriction in input
by Corion (Patriarch) on Jan 29, 2009 at 14:16 UTC

      Here is a simple example using Term::ReadKey. The script prompts for a name and reads the input character by character (as they are entered) until a newline is found or the input reaches 15 characters:

      use strict; use warnings; use Term::ReadKey; $!++; print "Enter name: "; my $key; my $name = ""; my $count = 0; ReadMode 4; while ($count < 15){ while (!defined ($key = ReadKey(-1))){ # Waiting for key pressed } last if ($key eq "\n"); print $key; $name .= $key; $count++; } ReadMode 0; # do whatever you want with your input, for example, print it: print "\n$name\n";

      citromatik

Re^3: restriction in input
by lostjimmy (Chaplain) on Jan 29, 2009 at 14:37 UTC
    I would handle this by just using the normal chomp($name = <STDIN>), checking its length, and then prompting the user to either accept the truncated name (eg much_too_long_name would become much_too_long_n) or to re-enter a shorter name. A simple looping prompt. You would do something similar if you were looking for a number and the user entered a string.