Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

How to declare and use global variables

by alih110 (Novice)
on Nov 03, 2008 at 12:49 UTC ( #721083=perlquestion: print w/replies, xml ) Need Help??
alih110 has asked for the wisdom of the Perl Monks concerning the following question:


I have an object oriented perl script with a top level script and a lot of perl packages. I need to declare a global variable and use it in the top level script and in one of the perl package. I tried declaring the variable with "our $variable_name" but it is not working for me. It gives the following error =>

"Global symbol "$make_AR_1" requires explicit package name at ....."

Any idea how to declare and use the global variables in perl?

I tried declaring the global variable in the top level script as well as in the perl package.


Replies are listed 'Best First'.
Re: How to declare and use global variables
by almut (Canon) on Nov 03, 2008 at 14:06 UTC

    From the docs:

    An "our" declaration declares a global variable that will be visible across its entire lexical scope, even across package boundaries.

    Note that separate files each do have their own lexical scope...

    Personally - in the few cases that I want to use global variables - I refer to them fully qualified ($Inst::make_AR_1 in this case). The additional typing required every time make me rethink whether I really want to have the variable global :)

      Are you consistent? That is, you always write $main::_ and @main::ARGV instead of $_ and @ARGV?

        No...  Inconsistency is a personality trait of mine which sometimes comes in handy :)

Re: How to declare and use global variables
by JavaFan (Canon) on Nov 03, 2008 at 12:57 UTC
    Could you show us some code? Otherwise, people will just have to guess what you've done wrong.
      sure ... In => ----------------------- our $make_AR_1; if ($make_AR_1 == 1) { $use = randInt(1,3); $make_AR_1 = 0; } ----------------------- In the top level script => --------------------------- use Inst; : : : $make_AR_1 = 1; : : : ----------------------------
        Well, you never declare $make_AR_1 in the top level script, and you're not saying you're exporting $make_AR_1, so it's not surprising you get a message when using $make_AR_1 in the top level script.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://721083]
Approved by rovf
[ovedpo15]: how fast and a good way to print error if more than one out of three variables are defined? for example if there are $a $b $c. I want that if for example $a and $b are defined - print error (also for $a and $c or $b and $c)
[ovedpo15]: its easy with three "if"s or one long "if" but is there a "nice" way :)

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2018-04-22 13:10 GMT
Find Nodes?
    Voting Booth?