Re: Some sort of scoping problem



On 6 Mai, 03:04, Mintcake <t...@xxxxxxxxxxxxxx> wrote:
package Foo;

my @xyzzy = (1,2,3);

sub new {
my $self = bless {}, shift;
$self->ini('xyzzy');
print \@xyzzy, ' ', scalar @xyzzy;
print $self->{xyzzy}, ' ', scalar @{$self->{xyzzy}};

}

sub ini {
my ($self, $field) = @_;
eval "\$self->{$field} = \\\@$field";

}

1;

My main program is simply this:

#!/usr/local/bin/perl -l
use Foo;
new Foo;

The two lines of output are:

ARRAY(0x90edda4) 3
ARRAY(0x90edfcc) 0

First I run your program with

use warnings;

enabled, and here I got the message:

Variable "@xyzzy" is not available at (eval 1) line 2.

Which means @xyzzy can't be seen from within eval. Things are
different if I "use" the variable inside the routine, so that
the compiler can see it - for example by writing

sub ini {
my ($self, $field) = @_;
print "ini: ", \@xyzzy,"\n";
eval "\$self->{$field} = \\\@$field";
}

You can also put the usage after the eval; it is only important
that the variable is used somewhere in the function:

sub ini {
my ($self, $field) = @_;
eval "\$self->{$field} = \\\@$field";
print "ini: ", \@xyzzy,"\n";
}

In both cases, Foo::new will print the same value for the hash.

We learn two things from this:

(1) Perl can be pretty bizarre in its details.
(2) If you do not "use warnings", you are automatically in a state of
sin.

Ronald
.