[comp.lang.perl] Which variables must be local ?

jand@kuling.UUCP (Jan Dj{rv) (02/28/90)

I have never quite figured out if the "predefined" variables like
$_, $1, $2, $' and so on must be declared as local when used in a sub.

My scripts seem to work regardless...

If there are some variables that are automatically local, I'd like to know
which.

If not, may I suggest that variables in pattern matching ($<digit>, $', $`,
$+, $&) and $_ be made automatically local in subs.

Just curious,

	Jan D.


lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (03/07/90)

In article <1421@kuling.UUCP> jand@kuling.UUCP (Jan Dj{rv) writes:
: I have never quite figured out if the "predefined" variables like
: $_, $1, $2, $' and so on must be declared as local when used in a sub.
: 
: My scripts seem to work regardless...
: 
: If there are some variables that are automatically local, I'd like to know
: which.
: 
: If not, may I suggest that variables in pattern matching ($<digit>, $', $`,
: $+, $&) and $_ be made automatically local in subs.

The pattern matching variables (but not $_) are all automatically local
to the current block, not just to subs.  This isn't a high overhead item
because they all just follow the pointer back to the structure describing
the last pattern match, and that pointer is saved and restored on block
entry and exit.  That's always been true from the very beginning.

The variables
	$_ $/ $, $" $\ $# $$ $? $* $0 $[ $] $; $! $@ $< $> $( $) $:
are all globals, and must be localized with local().  Not even a package
declaration changes this, since only variables starting with alphabetic
characters are local to a package.

The variables
	$% $= $- $~ $^ $|
are all tied to the currently selected output filehandle.  You don't use
local on these directly; you say
	local($old) = select(FOO); $| = 1; select($old);

The variable $. is tied to the filehandle that last did input.  You can,
as of patch 12, use local($.), which in fact doesn't localize the value of
$., but localizes the filehandle it refers to, and restores that when the
scope of the local is left.

Did I leave any out?

Larry