For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > July 2005 > Problem using "my" to protect scope









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 Problem using "my" to protect scope
careybunks@gmail.com

2005-07-24, 8:29 pm

Hi All,

I've written a program that passes an array of arrays (a very simple
one) to a subroutine. In the sub, a locally scoped copy is made using
"my". However, changing the value of the copy in the sub also changes
the value in the calling program. I thought this wasn't supposed to
happen. Can anyone help me explain why?

Here is the program:

-------------------------------------------------------------

#!/usr/bin/perl -w

@p = ([1, 7]);
print "@{$p[0]}\n";
modval(@p);
print "@{$p[0]}\n";

sub modval {
my @p = @_;

$p[0]->[0]++;
}


-------------------------------------------------------------

I'm expecting the output of the program to be:

1 7
1 7

But what I get is:

1 7
2 7

Any ideas?

Thanks,

CB

Sponsored Links







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

Copyright 2008 codecomments.com