Home > Net >  Why in the second run of the script, it is first displayed "Not OK", and then displayed &q
Why in the second run of the script, it is first displayed "Not OK", and then displayed &q

Time:09-17

I want to write a regex with output "OK" and "Not OK", without using constructs if, else:

validator_2.pl:

#!/usr/bin/perl

use strict;
use utf8;
use locale;
use warnings;
use 5.10.0;

my $input = <STDIN>;
say "OK" if $input =~ m/^\ 7\s\(\d{3}\)\s\d{3}-\d{2}-\d{2}$/ || say "Not OK";
$ echo " 7 (921) 123-45-67"|./validator_2.pl 
OK
$ echo " 7 (921) 123-45-67888888"|./validator_2.pl 
Not OK
OK

CodePudding user response:

Please study the following demonstration sample code

Note: phone number validation quite complicated task, regex is not right approach for this purpose

use strict;
use warnings;
use feature 'say';

my $re = qr/^\ 7\s\(\d{3}\)\s\d{3}-\d{2}-\d{2}$/;

while( my $input = <DATA> ) {
    chomp($input);
    say "$input : ", ($input =~ /$re/) ? 'Ok' : 'Not OK';
}


__DATA__
 7 (921) 123-45-67
 7 (921) 123-45-67888888

Output

 7 (921) 123-45-67 : Ok
 7 (921) 123-45-67888888 : Not OK
  •  Tags:  
  • perl
  • Related