For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > July 2005 > "my" value changed in subroutine changes value in main!?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author "my" value changed in subroutine changes value in main!?
careybunks@gmail.com

2005-07-24, 8:29 pm

The following code illustrates my problem. I've defined an array of
arrays, @vals, in that I pass into a subroutine "modval". Although I
thought the scope of the array in the subroutine was limited by the
"my" operator, on leaving the sub, the array in the main scope has its
value changed. Any advice?

Here is the output from the program (with a comment that indicates what
I think I should be getting):

Before call
0 x
1 y
Index = 1

Entered call
0 x
1 y
Index = 1

Returning from call
0 x
2 y
Index = 2

After call
0 x
2 y <---------- Here I am expecting "1 y"
Index = 1



----------------Program Follows---------------------------


#!/usr/bin/perl -w

$indx = 1;
@p = ([0, 'x'], [1, 'y']);

print "Before call\n";
foreach $k (@p) {print "@{$k}\n"}
print "Index = $indx\n";

modval($indx, \@p);

print "\nAfter call\n";
foreach $k (@p) {print "@{$k}\n"}
print "Index = $indx\n";

sub modval {
my $indx = shift @_;
my @p = @{shift @_};

print "\nEntered call\n";
foreach $k (@p) {print "@{$k}\n"}
print "Index = $indx\n";

$p[$indx][0]++;
$indx++;

print "\nReturning from call\n";
foreach $k (@p) {print "@{$k}\n"}
print "Index = $indx\n";
}

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com