On Wed, 02 May 2001 23:27:28 -0400, Randall Perry wrote:
>I'm baffled by perl's scoping of variables. In the code below, the
>$cust_data hash ref is inited outside the while loop. It's then set in the
>while with the results of a PgSQL query.
>
>In the if-else statement $cust_data can be seen in the 'if' but not in the
>'else' (if I try to print a value in else, $cust_data->{'customer'}, I get
>an undeclared variable error).
No sir. You're wrong. And scoping has nothing to do with it. For this
source file, it is just as if it was a global variable.
>use strict;
>$cust_data = {};
This is an initial setting. Where's the "my"? Or else, do
use vars '$cust_data';
>while ($condition) {
> ...
>
> $cust_data = get_cust_data();
Here's you're throwing away the previous value of $cust_data, and
overwriting it with the return value of get_cust_data(). This just might
return undef, for all I care.
> if ($condition2) {
> if (send_mail($cust_data)) {
> print $cust_data->{'customer'};
This works, so $cust_data has been set properly.
> ...
> }
> else {
> if (send_mail($cust_data)) {
> print $cust_data->{'customer'};
This doesn't. Is there some correlation between the return value of
get_custom_data() and the value of $condition2? There must be. My guess
is that get_custom_data() returned undef.
> ...
> }
>}
Now, in order to make scoping really confusing:
if(my $cust_data = get_cust_data()) {
# do something with it
} else {
...
}
Now, in the "else" part, the lexical variable $cust_data can still be
seen! So its scope is not limited to the "if" block, but it includes the
"else" block, and any "elsif" blocks in between.
--
Bart.