Perl utilfuncs

utilfuncs.pm

use strict;
 
# regex count: Returns the number of times
#                    that a pattern is found in a string
sub regexcnt
{
   my ($str, $pattern) = @_;
   my $cnt = 0;
   my $pos = -1;
 
   while (($pos = index($str, $pattern, $pos)) > -1)
   {
      $cnt++;
      $pos++;
   }
 
   return $cnt;
}
 
###############
 
sub askQuestion
{
   my ($question, $valid_answers_ref, $case_sensitive) = @_;
   my $answer;
   my $valid_answer = 0;
 
   $case_sensitive = 0 if not defined $case_sensitive;
 
   while (not $valid_answer)
   {
      print $question;
      $answer = <STDIN>;
      chomp ($answer);
 
      last if not defined $valid_answers_ref;
 
      # Otherwise, check against valid answers
      foreach (@$valid_answers_ref)
      {
         if ($case_sensitive)
         {
            if ($answer eq $_)
            {
               $valid_answer = 1;
               last;
            }
         }
         else
         {
            if (uc $answer eq uc $_)
            {
               $valid_answer = 1;
               last;
            }
         }
 
      } # end foreach valid answer
 
      print "Invalid answer\n" if not $valid_answer;
 
   } # end while not valid answer
 
   return $answer;
 
} # End askQuestion
 
# Module returns a true value
1;
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License