First, I've got to say that I didn't know that a global
pattern match returned an array by default (i.e. no
memorization with brackets) of all the matches. I am only
beginning to imagine what that could do in conjunction with
map.
So, all you really need is a better regexp:
@stuff = m#(?:[^\\]|^)(\$(?:[a-zA-z_][a-zA-z0-9]*|[0-9]))#g;
This ensures that the variable is not prefixed by a backslash,
or that it is at the beginning of the line ('^'). The 'questionable'
brackets '(?: ...)' are just groupings that aren't memorized,
in case you aren't familiar with that modifier.
Still, you're open to scenarios where things that look like
variables, but aren't, are picked up for whatever reason.
This could include something you have in comments, single-quoted
or qX-quoted strings, or wierd stuff getting pulled out
of regular expressions.
So, the regexp above is intentionally a bit tame, and it
won't pick up on some common things, such as:
\$x; # A reference to $x, but ignored by regexp
${x}; # Same as $x, but ignored
$x[10]; # Shows up as $x, but is really @x
So, the utility of this match is limited, but hopefully it
will suit your needs.