in reply to using \x in regex

The regex is looking for a ~ anywhere in $key, while it sounds like what you want is to compare against the entire value in $key. For example:
if ($key eq "~") { # it's a tilde } elsif ($key eq "\e[5~") { # pgup } elsif ($key eq "\e[6~") { # pgdown }