in reply to Variable access across packages?

use strict; use warnings; package B; our $foo = 3; package main; print $B::foo, "\n";

If you don't want the $B::foo notation, have a look at Exporter

Replies are listed 'Best First'.
Re^2: Variable access across packages?
by shmem (Chancellor) on Nov 14, 2007 at 18:21 UTC
    Qualifying is a good idea, but not necessary with our
    use strict; use warnings; package B; our $foo = 3; package main; print "foo is >$foo<\n"; __END__ foo is >3<

    as opposed to use vars:

    use strict; use warnings; package B; use vars qw($foo); $foo = 3; package main; print "foo is >$foo<\n"; __END__ Global symbol "$foo" requires explicit package name at - line 10. Execution of - aborted due to compilation errors.

    our creates a lexically scoped alias (file scoped, in this case) of a variable which is visible through package boundaries. So, $foo in the first example is an alias for $B::foo, but it is visible in package main, too (but still refers to the SCALAR slot in the $B::foo typeglob.

    Consider:

    use strict; use warnings; { package B; our $foo = 3; } package main; print "foo is >$foo<\n"; __END__ Global symbol "$foo" requires explicit package name at - line 10. Execution of - aborted due to compilation errors.

    IMHO the "(obsolete)" note in vars NAME section is plain wrong.

    ;-)

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re^2: Variable access across packages?
by porta (Sexton) on Nov 14, 2007 at 14:22 UTC
    Thanks, moritz, for the reply...
    But I'm looking for something different.
    In your example, main is a package and access a variable declared in package B.
    In my problem, main is not a package but a script and it *uses* B. And I want B to access a variable declared in main without passing it as a argument in a subroutine call.
      every script implicitly runs in the namespace main, so you can just revert the logic and access $main::VariableName if you declared it with our.

      See perlmod for details.

      And I want B to access a variable declared in main
      while this is possible (with global variables) it's generally not a good idea. why give up the modularity gained from using a module if there are other ways to solve it?