Re: [MacPerl] Perl Scope problem

From: Bart Lateur <bart(dot)lateur(at)skynet(dot)be>
To: <macperl(at)perl(dot)org>
Cc: <pgsql-general(at)postgresql(dot)org>
Subject: Re: [MacPerl] Perl Scope problem
Date: 2001-05-03 07:15:01
Message-ID: tp02ftguvlordiasah3l2foubg0bi0o126@4ax.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

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.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Diana Cionoiu 2001-05-03 07:39:10 troubles with postgresql 7.0.2
Previous Message Jörg Wallerich 2001-05-03 07:13:40 Re: Trigger won't accept function (Please Help)