secret has asked for the wisdom of the Perl Monks concerning the following question:

Hello esteemed Monks,

I have the following pm file :

use strict ; use warnings ; package FOO ; sub Principal::bof { my $fic = "toto" ; bof2() ; } sub bof2 { print $fic } 1;
Which is loaded by a script like this :
use strict ; use warnings ; package Principal ; require ("ot.pm") ; Principal::bof() ;
This fails with  Global symbol "$fic" requires explicit package name .

I tried to do print $FOO:fic or print $Principal::fic in the bof2 sub but then it fails with Use of uninitialized value in print

I don't understand the namespaces relations in this . Is there a way i can access the value from bof2() without passing it as parameter ?

Thanks if you can help .

Replies are listed 'Best First'.
Re: accessing $var problem due to package and subs
by ikegami (Patriarch) on Apr 05, 2006 at 16:42 UTC

    Lexical (my) variables aren't accessible outside of the curlies or file they are in. Use package variables instead. You probably want to use local in addition to our to prevent the clobbering of any existing value.

    use strict ; use warnings ; package FOO ; sub Principal::bof { our $fic; # Save us from typing $FOO::fic. local $fic = "toto"; # 'local' restores $fic when we exit this sub # The above can be combined into: # local our $fic = "toto"; bof2(); } sub bof2 { our $fic; # Save us from typgin $FOO::fic. print $fic; } 1;

    our doesn't create the variable if it already exists. our simply disables use strict 'vars' for the specified var within the curlies it is in. The variable continues to exist outside of the curlies.

Re: accessing $var problem due to package and subs
by eric256 (Parson) on Apr 05, 2006 at 16:54 UTC

    I beleive you can just declare $fix in the scope of the FOO package instead of the sub. The following appears to do what you want.

    use strict; use warnings; { package FOO; my $fic; sub Principal::bof { $fic = "toto"; bof2(); } sub bof2 { print $fic; } } Principal::bof();

    ___________
    Eric Hodges