#!/usr/bin/perl -w
# -T can only be given on the command line (taint checking)
use strict; # homework by Eric Auer...
use English; # to have $MATCH $PREMATCH $POSTMATCH

sub hakenchecker { # check if string has nice () nesting
  my $a =  $_[0]; # copy arg
  my $ident = $_[1]; # for debugging
  my $pre;
  my $post;

  $ident = (!$ident) ? 1 : ($ident+1); # for debugging

  if (!$a) { return 1; } # empty string is always ok
  if ($a !~ /(\(|\))/) {
    print STDERR ("  " x $ident) . "Part ok: <$a>\n";
    return 1;
  } # true if no ( or ) at all

  unless ( $a =~ /\([^\(\)]*\)/ ) { # $& is the match (ungreedy)
    # this time we match only a pair with no () inside!
    print STDERR ("  " x $ident) . "Failed, because <$a>\n";
    return 0; # string with only ( or only ) or only ) ... (
  }

  $pre = $PREMATCH;
  $post = $POSTMATCH;
  $a = substr($MATCH,1); # remove ( at the beginning
  chop $a; # remove ) at the end

  print STDERR ("  " x $ident) . "Recurse: <$pre,$a,$post>\n";
  return (  &hakenchecker($pre . $post, $ident)
         && &hakenchecker($a,   $ident) ); # modified!
}


print "Checknest, version 2\n\n";
print "Is a((b)cde) ok ?\n";
print "" . ((&hakenchecker("a((b)cde)")) ? "yes" : "no") . "!\n";

print "Is a((b)(cd)e) ok ?\n";
print "" . ((&hakenchecker("a((b)(cd)e)")) ? "yes" : "no") . "!\n";

print "Is a(b)cde) ok ?\n";
print "" . ((&hakenchecker("a(b)cde)")) ? "yes" : "no") . "!\n";

