scope question

Discussion in 'Perl Misc' started by Richard Trahan, Jul 4, 2005.

  1. 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.
    Richard Trahan, Jul 4, 2005
    #1
    1. Advertising

  2. 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
    Tad McClellan, Jul 4, 2005
    #2
    1. Advertising

  3. Richard Trahan

    Joe Smith Guest

    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
    Joe Smith, Jul 4, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Opal
    Replies:
    12
    Views:
    933
    Paul Opal
    Oct 11, 2004
  2. ann
    Replies:
    13
    Views:
    653
    Patricia Shanahan
    Sep 13, 2005
  3. Steven T. Hatton
    Replies:
    9
    Views:
    462
  4. Xah Lee
    Replies:
    0
    Views:
    2,223
    Xah Lee
    Feb 26, 2009
  5. Replies:
    0
    Views:
    157
Loading...

Share This Page