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

Dear Gurus, in my scripts just after execution user needs to input several information`s as a prompt answer. One of the information which needs to be checked is user name. On our server we are using special name convention which looks like this: usr123 - 3 letters and 3 diggits I would like to implement some rule which will check if user input fit to current name convention (3 letters and 3 diggits). I started writing some script but I stuck here. Maybe somebody will be able to help me.
#!/usr/bin/perl use warnings; use strict; print "OS username:"; my $os_user = <>; chomp $os_user; #remove "\n" on the end of entered string ... ?
Thanks in advance for any ideas. Zalezny

Replies are listed 'Best First'.
Re: Checking name convention
by AppleFritter (Vicar) on Feb 24, 2015 at 11:36 UTC

    Use a regular expression:

    # ... unless($os_user =~ m/^[A-Za-z]{3}[0-9]{3}$/) { die "Invalid username: $os_user"; } # ...

    Depending on what letters and digits are allowed exactly (Unicode has a bunch more), you may want to use \p{IsAlpha} and/or \p{IsDigit} instead of [A-Za-z] and [0-9], too -- though you'll also have to use open IO => ':encoding(UTF-8)', ':std'; for that.

      Thank You very much for Your efficient support! It seems that is this, what I`m looking for. :))) God bless, Zalezny
Re: Checking name convention
by Stringer (Acolyte) on Feb 24, 2015 at 15:01 UTC
    You can use a regular expression to look for the pattern, and an until loop to keep prompting the user until their input matches your desired pattern:
    my $os_user = '&'; #stop warnings from yelling at you print "OS username:"; until ($os_user =~ /^[A-Za-z]{3}\d{3}$/) { chomp($os_user = <>); }

      Because no  $ end-of-string anchor is used, the  /^[A-Za-z]{3}\d{3}/ match may allow something improper:

      c:\@Work\Perl\monks>perl -wMstrict -le "my $os_user = 'foo9876543210'; $os_user =~ /^[A-Za-z]{3}\d{3}/ or die qq{bad user name: '$os_user'}; print qq{'$os_user' is ok by me!}; " 'foo9876543210' is ok by me!
      See above for a variation that avoids this problem. See also perlre, perlrequick, and perlretut.


      Give a man a fish:  <%-(-(-(-<

        Woops, you're right. Updated it with the requisite anchor.