in reply to (tye)Re: Variable scoping in packages
in thread Variable scoping in packages

You're not going to get away with just a teaser, you know.

  • Comment on Re: (tye)Re: Variable scoping in packages

Replies are listed 'Best First'.
Re: Re: (tye)Re: Variable scoping in packages
by chromatic (Archbishop) on Oct 10, 2001 at 03:57 UTC
    Define a package:
    package Pack; my $foo = 'pack'; sub import { my $pkg = caller(); no strict 'refs'; *{ $caller . '::foo' } = \$foo; } 1;
    Now write a program:
    #!/usr/bin/perl -w use strict; use Pack; print "$foo\n";
    After realizing that names have scope, variables do not (Dominus once said something similar), print out this page. Then eat it. :) ©
      Dominus said:

        "Values don't have scope. Variables don't have scope. Only names have scope."

      This, along with a very enlightening explanation can be found at Re: typeglobs and filehandles.

      -Blake

      So that's pretty ordinary. The only reason, I suppose, why it normally "can't be done" is that the inherited sub import can't get at them. It would have to be told of the ref, not the name. Perhaps extending the syntax to have ['$name' => \$name] in the @EXPORTS list would do the trick. That is, you must give the name (that the user of the package will ask for) and the ref, since it can't find a ref by itself just given the name.

      —John