david
david

Reputation: 1016

What's the perl equivalent to a C file-scope variable, and how to use it in a sub?

Trying to understand packages, local, my, and references in perl. Consider the following script...

package z;
$x = 5;

sub q() { return $z::x };

printf "q() .. %d\n", q();

my $xr = \$x;

my $x = 7;

printf "xr .. %d\n",$$xr;

$$xr = 9;

printf "x .. %d\n", $x;

$$xr = 11;

printf "q() .. %d\n", q();

I expect each of the invocations of q() to return a number, but I'm not sure what they should return. Instead I get the following output...

q() .. 0
Argument "" isn't numeric in printf at src/demo/multi_my.pl line 8.
xr .. 5
x .. 7
q() .. 0
Argument "" isn't numeric in printf at src/demo/multi_my.pl line 22.

Upvotes: 0

Views: 50

Answers (1)

ikegami
ikegami

Reputation: 386331

q() is another way of writing ''. That's why q() is returning an empty string. Use a different name for your sub.


my declares a lexically-scoped variable. These are usually created by curlies, but the file is also a lexical scope. So if you want a variable scoped to a file, use my $x; outside of any curlies.


The first $x you access is globally-scoped; it's visible as $z::x throughout the program.

Upvotes: 4

Related Questions