use strict; use warnings; while(my $input = ){ print "input: $input\n"; my $level = 0; my $tab = "| "; my %action = ( '(' => sub { print "\n", $tab x ++$level, shift }, ')' => sub { print "\n", $tab x $level--, shift }, 'default' => sub { print shift }, ); ( $action{$_} // $action{'default'} )->($_) for $input =~ /./g; print "\n\n\n"; } __DATA__ A (B C D) A (B C D) (E F G) A B (C (D E) (F G)) (H I) #### input: A (B C D) A | (B C D | ) input: A (B C D) (E F G) A | (B C D | ) | (E F G | ) input: A B (C (D E) (F G)) (H I) A B | (C | | (D E | | ) | | (F G | | ) | ) | (H I | )