scope question

R

Richard Trahan

Consider the following code:

use strict;
{
my $x = 5;
our $sr = sub { print "$x\n"; };
}
&$sr;

This code gives a scope error, but if I remove 'use strict',
it works ok.

The 'our $sr' statement should make an entry in the SCALAR
slot of *main::sr, right? And the &$sr should retrieve only
that value, right?

What am I missing here?

Thanks.
 
T

Tad McClellan

Richard Trahan said:
Consider the following code:

use strict;
{
my $x = 5;
our $sr = sub { print "$x\n"; };
}
&$sr;

This code gives a scope error, but if I remove 'use strict',
it works ok.

The 'our $sr' statement should make an entry in the SCALAR
slot of *main::sr, right?


Right, the value is there.

You are having trouble _accessing_ that value though.

What am I missing here?


All that "our" gets you is to make "use strict" shut up about using
short names rather than long names.

The "permission to use short names" is scoped, once outside that
scope, you must use the fully qualified package name again.

So:

&{$main::sr};
or
$main::sr->();

or, if you want to use the short name after the block, ask for that
with an

our $sr;

after the block.
 
J

Joe Smith

Richard said:
Consider the following code:

use strict;
{
my $x = 5;
our $sr = sub { print "$x\n"; };
}
&$sr;

With 'our', the value is global but the permission to access
it is scoped. It would work if you replace the last line with

{
our $sr;
&$sr;
}

-Joe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top