I\'m writing an abstraction function that will ask the user a given question and validate the answer based on a given regular expression. The question is repeated until the
You need to use the eval function. The below code will work:
sub ask {
my ($prompt, $validationRe, $caseSensitive) = @_;
my $modifier = ($caseSensitive) ? "" : "i";
my $ans;
my $isValid;
do {
print $prompt;
$ans = <>;
chomp($ans);
# What I want to do that doesn't work:
# $isValid = $ans =~ /$validationRe/$modifier;
$isValid = eval "$ans =~ /$validationRe/$modifier";
# What I have to do:
#$isValid = ($caseSensitive) ?
# ($ans =~ /$validationRe/) :
# ($ans =~ /$validationRe/i);
} while (!$isValid);
return $ans;
}