Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Proper use of the 'my' operator

Status
Not open for further replies.

RPrinceton

Programmer
Jan 8, 2003
86
US
Hi,
I am new to CGI and learning about many "quirks" associated with the language. The latest one deals with using the 'my' operator. My understanding of the 'my' operator is to simply make a variable local to a subroutine. It appears that it has much deeper implications e.g.,

The following code yields "abc and "def" written in my log file:
open (LOG, ">>log.txt");
$var1 = "abc";
$var2 = "def";
for(1..2){
$varname = "var".$_ ;
print LOG ${"$varname"},"\n";
}
close (LOG);

...while the following code yields empty values written in my log file by just adding the 'my' operator:

open (LOG, ">>log.txt");
my $var1 = "abc";
my $var2 = "def";
for(1..2){
my $varname = "var".$_ ;
print LOG ${"$varname"},"\n";
}
close (LOG);

Why is this any different?
The book I am learning from i.e., "Learning Perl" by O'Reilly does not go into the 'my' operator in any depth. It is imperative that I understand it thoroughly since I see it used all over the place. Any light is appreciated. Thanks in advance.
Regards,
Randall Princeton

 
The problem declarations are :

my $var1 = "abc";
my $var2 = "def";


Switching my to local fixes the problem.I agree though, its an odd case, at first glance I'd expect it to work as well and can not tell you exactly why its not.

For a more in-depth read on the subject check :

 
The way I understand it, my explicitly declares the variable name and memory space is allocated for it. If you use the strict statement in the shebang, you are forced to declare your variables before you use them, ie; you can't initialize a variable until it's declared.

There's always a better way. The fun is trying to find it!
 
I'm trying to learn too... what does your
Code:
${"$varname"}
doing exactly?

Kevin
A+, Network+, MCP
 
Using ${"$varname"} is a method of dereferencing a value. It allows you to dynamically access variable names.

So if $varname is equal to 'IAMSAM'

${"$varname"}

is the same as saying $IAMSAM

 
Ok, I get it, it's basically dereferencing $varname.

Also, I found this:
"Only package variables are visible to symbolic references. Lexical variables (declared with my) aren't in a symbol table, and thus are invisible to this mechanism."
From here:


Kevin
A+, Network+, MCP
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top