Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm polling the user for a list of words separated by commas. The code is below. How can I check the input to make sure that it contains only letters and commas?
print "Enter words separated by commas."; my $answer=<STDIN>;

Replies are listed 'Best First'.
•Re: Validating User Input
by merlyn (Sage) on Jun 10, 2002 at 15:51 UTC
    Well, it'll have a newline until you chomp it, so the answer is always "never". {grin} After chomping though:
    print "Enter words separated by commas."; chomp(my $answer=<STDIN>); die "Invalid input" if $answer =~ tr/a-zA-Z,//c;

    -- Randal L. Schwartz, Perl hacker

      Interesting, what occured to me first was /^[a-zA-Z,]+$/. However, I'm guessing there's a reason you used tr. Mind if I ask why?
      _______________
      D a m n D i r t y A p e
      Home Node | Email