Chas. Owens wrote:
On Thu, Mar 20, 2008 at 5:26 AM, sanket vaidya <[EMAIL PROTECTED]> wrote:
use warnings;
use strict;
my $name = "sanket";
$fred::name = "Fred;
print "In main name = $name\n";
package Fred;
print "Now name = $name";
The output is
In main name = sanket
Now name = sanket
why so?
why the out put is not:
In main name = sanket
Now name = Fred
First off, don't do that. Messing around with another package's
variables ties you to that version of the module and is bad juju.
Not sure I understand how the OP's question motivates that remark.
To get the output you desire use the our function to declare $name
in Fred
Even if that solution 'works', it results in the warning ""our" variable
$name masks earlier declaration in same scope". The reason is that our()
is lexically scoped, not package scoped.
Please consider this example:
C:\home>type test.pl
use warnings;
use strict;
my $name = 'sanket';
$Fred::name = 'Fred';
print "$name\n";
package Fred;
our $name;
print "$name\n";
package main;
print "$name\n";
C:\home>perl test.pl
"our" variable $name masks earlier declaration in same scope at test.pl
line 9.
sanket
Fred
Fred
C:\home>
The third print() statement, even if within package main, outputs the
package variable $Fred::name. In other words, since the our()
declaration in package Fred is not restricted to a block, it's effective
from the point of its location and throughout the rest of the file.
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/