Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > Perl Misc > scope question

Reply
Thread Tools

scope question

 
 
Richard Trahan
Guest
Posts: n/a
 
      07-04-2005
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.
 
Reply With Quote
 
 
 
 
Tad McClellan
Guest
Posts: n/a
 
      07-04-2005
Richard Trahan <> wrote:
> 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.


--
Tad McClellan SGML consulting
Perl programming
Fort Worth, Texas
 
Reply With Quote
 
 
 
 
Joe Smith
Guest
Posts: n/a
 
      07-04-2005
Richard Trahan wrote:
> 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Lexical scope vs. dynamic scope Xah Lee Java 0 02-26-2009 10:08 AM
CSPEC issue: lossing scope (or incorrect scope) in cspec subroutine. balldarrens@gmail.com Perl Misc 0 02-05-2009 08:42 PM
Scope - do I need two identical classes, each with different scope? ann Java 13 09-13-2005 03:07 AM
How do namespace scope and class scope differ? Steven T. Hatton C++ 9 07-19-2005 06:07 PM
IMPORT STATIC; Why is "import static" file scope? Why not class scope? Paul Opal Java 12 10-10-2004 11:01 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57