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

I have a perl package 'A' in which i have defined a variable in global section. This package has two subroutines.Assume i have a perl script in which i am creating object of package 'A'.Using this object i am calling 2 functions of A.My question is,how many times will the variable in global section be redefined out of these 3 actions : object creation,function 1 call , function 2 call

Replies are listed 'Best First'.
Re: Perl package scope of global variables
by haukex (Archbishop) on Feb 06, 2019 at 19:56 UTC

    Like the others, I think some sample code would go a long way to explain what you are asking. At the moment, from your description, I am imaginging you mean code like what AnomalousMonk showed. If that is the case, then what you might be asking about is "fields" or "properties" of objects...? A global variable (or more specifically, a "package variable") defined with our is neither, it's simply one variable that has nothing to do with the object's fields, the variable will not normally be affected by object creation. If you're asking about how to define fields, then I can suggest the chapter Objects in Modern Perl (you might want to start with the section "Blessed References" to see how Perl's native OO support works, or maybe perlootut).

Re: Perl package scope of global variables
by AnomalousMonk (Archbishop) on Feb 06, 2019 at 19:27 UTC

    I don't understand the terminology you are using.

    I have a perl package 'A' in which i have defined a variable in global section.

    What is the "global section" of a Perl package?

    ... how many times will the variable in global section be redefined out of these 3 actions : object creation,function 1 call , function 2 call

    I don't understand the word "redefined" in this context. Do you perhaps mean "accessed", either for read or write?

    As already suggested, here's some code to perhaps provide a basis for discussion:

    c:\@Work\Perl\monks>perl -wMstrict -le "{ package A; our $count = 0; ;; sub new { my $class = shift; ++$count; return bless [ @_ ] => $class; } ;; sub ding { my $self = shift; print 'ding'; return ++$count; } } ;; print 'count is: ', $A::count; ;; print 'create A object'; my $oa = A->new('hi there'); print 'count is: ', $A::count; ;; $oa->ding; print 'count is: ', $A::count; ;; $oa->ding; print 'count is: ', $A::count; " count is: 0 create A object count is: 1 ding count is: 2 ding count is: 3


    Give a man a fish:  <%-{-{-{-<

Re: Perl package scope of global variables
by Anonymous Monk on Feb 06, 2019 at 18:37 UTC
    Code not words :) Try it and see :) Code outside of subroutines runs once