$ cat t.pl #!/usr/bin/perl use strict; use warnings; # Function to accept only 4 digit numbers my $v_4dig = gen_validator('^\d{4}$'); # Function to accept only 3 digit numbers my $v_3dig = gen_validator('^\d{3}$'); # Function to accept only lower-case alphabetic strings my $v_alpha = gen_validator('^[a-z]+$'); for my $t ('apple', 123, 456, 7890) { print "$t:\t", $v_4dig->($t), "\t", $v_3dig->($t), "\t", $v_alpha->($t), "\n"; } sub gen_validator { my $regex = shift; # Create function to validate against current regex return sub { my $data = shift; return 1 if ! defined $data; if (ref $data eq '') { return 1 if $data =~ /$regex/; } return 0; } } $ perl t.pl apple: 0 0 1 123: 0 1 0 456: 0 1 0 7890: 1 0 0