in reply to using foreach

One additional Perl-ish point for you to be aware of here... :-)

$#stack1 is the index of the last element of the array @stack1. But the stack size is arguably the length of the array, which is given by @stack1 in a scalar context (i.e,  scalar @stack1 to be unambiguous).

Happy Perl-ing.