http://www.perlmonks.org?node_id=1064605

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 (Cardinal) 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.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ