#!/usr/bin/perl -w

# matchtest.pl

#    VERSION: 1 (5 September 2003)
#    PURPOSE: Facilitates testing of regular expressions
#    INPUT: From keyboard
#        1. input string
#        2. regular expression
#    OUTPUT: To monitor, either "Expression ... found" or "Expression ... not found"

############## LIBRARIES AND PRAGMAS ################
  use strict;

#################### VARIABLES ######################

my $true = 1;                # used to assign truth value 
my $false = 0;               # used to assign truth value 
my $wants_to_stop;           # false until user wants out
my $answer;                  # response from yes/no question
my $string;                  # string to be searched
my $new_string;              # string offered by user. If blank, use old string
my $regex;                   # regular expression used in matching
my $new_regex;               # regular expression offered by user.
                             #   If blank, use old regular expression

################### MAIN PROGRAM ####################

  do {

     $answer = Yes_or_no("Want to try a regular expression? (yes or no) ");

     if ($answer eq "yes") {          # user wants a go at it
        $wants_to_stop = $false;
          ### get string to be searched and regular expression
        $new_string = Get_string("Enter a line of text to be searched (or nothing to retain previous line)\n    TEXT: ");
        if ($new_string ne "") {$string = $new_string};
        $new_regex = Get_string("Enter a regular expression (or nothing to retain previous expression)\n     EXPRESSION: ");     
        if ($new_regex ne "") {$regex = $new_regex};
          ### print results
        print "Expression '$regex' ";
        if ($string =~ /$regex/) {print "FOUND\n"} else {print "NOT FOUND\n"}
     } else {                         # user wants to stop
        $wants_to_stop = $true;
     }

  } until ($wants_to_stop);

  print "\n\n", "Thank you for using matchtest!", "\n";

#################### SUBROUTINES ####################

sub Get_string {
# Prints prompt given from subroutine call
# Gets input from user (removes ENTER) and returns it

  my $prompt = $_[0];
  print $prompt;
  my $string = <STDIN>;
  chomp $string;
  return $string;
}

sub Yes_or_no {
# Prints prompt given from subroutine call
# Forces yes/no response from user
# Returns answer in lower case

  my $prompt = $_[0];
  my $answer = "";
  until ($answer eq "yes" | $answer eq "no") {
    print "\n", $prompt;
    $answer = lc(<STDIN>);
    chomp $answer;
  }
  return $answer;
}