B
Bill
I've been programming perl for a while now and I can't believe something so
simple is confusing me. Take a look at the following code:
-------------------------
#!/usr/bin/perl -w
# global array definition
my @array = ("a","b","c");
sub print_array {
foreach my $element (@array) {
$element .= "9";
print $element . "\n";
}
}
for ($i = 0; $i < 3; $i++) {
&print_array();
}
------------------------
The output is as follows:
a9
b9
c9
a99
b99
c99
a999
b999
c999
What I expected was:
a9
b9
c9
a9
b9
c9
a9
b9
c9
I thought that "my" would make a copy of each array element whose scope was
limited to the subroutine in which it was defined. But it seems that
modifying the elements locally is modifying them in the global array as
well. What am I missing here?
-Bill
simple is confusing me. Take a look at the following code:
-------------------------
#!/usr/bin/perl -w
# global array definition
my @array = ("a","b","c");
sub print_array {
foreach my $element (@array) {
$element .= "9";
print $element . "\n";
}
}
for ($i = 0; $i < 3; $i++) {
&print_array();
}
------------------------
The output is as follows:
a9
b9
c9
a99
b99
c99
a999
b999
c999
What I expected was:
a9
b9
c9
a9
b9
c9
a9
b9
c9
I thought that "my" would make a copy of each array element whose scope was
limited to the subroutine in which it was defined. But it seems that
modifying the elements locally is modifying them in the global array as
well. What am I missing here?
-Bill