Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Scope of "our" Variable in package

by dushyant (Acolyte)
on Nov 27, 2013 at 12:54 UTC ( #1064605=perlquestion: print w/replies, xml ) Need Help??
dushyant has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I am trying to understand the scope of our variables using below simple code.

#!/usr/bin/perl -w #use strict; our $hometown = "rajkot"; our $state = "gujarat"; print "Main hometown : $hometown\n"; print "Main state : $state\n"; package dushyant; print "dushyant first hometown : $hometown\n"; print "dushyant first state : $state\n"; print "dushyant main hometown : $main::hometown\n"; print "dushyant main state : $main::state\n"; package parmar; our $hometown = "parmar_rajkot"; our $state = "parmar_gujarat"; print "parmar hometown : $hometown\n"; print "parmar state : $state\n"; print "parmar main hometown : $main::hometown\n"; print "parmar main state : $main::state\n"; package suresh; print "suresh hometown : $hometown\n"; print "suresh state : $state\n"; print "suresh main hometown : $main::hometown\n"; print "suresh main state : $main::state\n"; package main; print "Main hometown : $hometown\n"; print "Main state : $state\n";

Output of the code is :

Main hometown : rajkot Main state : gujarat dushyant first hometown : rajkot dushyant first state : gujarat dushyant main hometown : rajkot dushyant main state : gujarat parmar hometown : parmar_rajkot parmar state : parmar_gujarat parmar main hometown : rajkot parmar main state : gujarat suresh hometown : parmar_rajkot suresh state : parmar_gujarat suresh main hometown : rajkot suresh main state : gujarat Main hometown : parmar_rajkot Main state : parmar_gujarat

Last four line of output is confusing. What i am thinking is that Either Suresh main hometown should be printed as parmar_rajkot or Main hometown should be printed as rajkot. So please help me to understand whats going on here.

Replies are listed 'Best First'.
Re: Scope of "our" Variable in package
by choroba (Bishop) on Nov 27, 2013 at 13:21 UTC
    Have you read our? Suresh main hometown remains "rajkot" as you do not change $main::hometown, "parmar_rajkot" is assigned to $parmar::hometown. Main hometown is printed as "parmar_rajkot", because the variable $hometown does not alias $main::hometown, but $parmar::hometown, as that's the package where you used our for the last time.
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1064605]
Approved by Corion
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2018-01-20 00:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How did you see in the new year?










    Results (226 votes). Check out past polls.

    Notices?