Change if (grep(/^$stack$/, @stack)) { to if (grep(/^\Q$stack$/, @stack)) {.
perlre for details.
The start of some sanity?
In reply to Re: Problems with a regex? by BrowserUk in thread Problems with a regex? by dwlepage