Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

accessing $var problem due to package and subs

by secret (Beadle)
on Apr 05, 2006 at 16:25 UTC ( #541424=perlquestion: print w/replies, xml ) Need Help??

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 ("") ; 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 (Pope) 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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://541424]
Approved by ww
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2020-02-17 12:59 GMT
Find Nodes?
    Voting Booth?
    What numbers are you going to focus on primarily in 2020?

    Results (71 votes). Check out past polls.