I was playing around with qw today and it got me thinking... I'm probably not the first one to do this but I couldn't find it anywhere else. This works since qw can take any non-alphanumeric separator.
sub is_balanced { my $string = shift; eval("qw($string)"); return 0 if $@; return 1; }
Here it is in action:
my $balanced = "(1 + 2 * (3 + (5/4) + 8) + 6)"; my $unbalanced1 = "(((1 + 2 * (3 + (5/4) + 8) + 6))"; my $unbalanced2 = "(((1 + 2 * (3 + (5/4) + 8) + 6))))"; printf("Is $balanced balanced? %s\n", balanced_parens($balanced) ? "ye +s" : "no"); printf("Is $unbalanced1 balanced? %s\n", balanced_parens($unbalanced1) + ? "yes" : "no"); printf("Is $unbalanced2 balanced? %s\n", balanced_parens($unbalanced2) + ? "yes" : "no");
prints:
Is (1 + 2 * (3 + (5/4) + 8) + 6) balanced? yes Is (((1 + 2 * (3 + (5/4) + 8) + 6)) balanced? no Is (((1 + 2 * (3 + (5/4) + 8) + 6)))) balanced? no
|
|---|