Confusion over instance variables, different objects

D

DJB

Hi all,

Perl 5.8.6 (ActiveState)
Spreadsheet::WriteExcel 2.15
Windows XP

I'm trying to resolve some confusion I have over two different objects
(seemingly) sharing the same instance variable data. In this case,
it's the _str_unique instance variable.

To see the problem in action, run the following snippet with a
debugger, and put a watch on $workbook->{_str_unique},
$worksheet->{_str_unique} and $self->{_str_unique}. Step into the
$worksheet->write method, and from there step into the write_string
method.

use strict;
use warnings;
use Spreadsheet::WriteExcel;

my $workbook = Spreadsheet::WriteExcel->new("test.xls");
my $worksheet = $workbook->add_worksheet();

$worksheet->write(0,0,"Hello");
$workbook->close();

After the write method, you'll notice that the
$worksheet->{_str_unique} instance variable is set to 1. That's
expected. What's NOT expected is that $workbook->{_str_unique} is also
set to 1. How did that happen?

Regards,

Dan
 
A

attn.steven.kuo

DJB said:
Hi all,

Perl 5.8.6 (ActiveState)
Spreadsheet::WriteExcel 2.15
Windows XP
(snipped)

use Spreadsheet::WriteExcel;

my $workbook = Spreadsheet::WriteExcel->new("test.xls");
my $worksheet = $workbook->add_worksheet();

$worksheet->write(0,0,"Hello");
$workbook->close();

After the write method, you'll notice that the
$worksheet->{_str_unique} instance variable is set to 1. That's
expected. What's NOT expected is that $workbook->{_str_unique} is also
set to 1. How did that happen?

Regards,

Dan


Refer to the source code on CPAN:

http://tinyurl.com/9sz3r

sub add_worksheet {

my $self = shift;
my $index = @{$self->{_worksheets}};

my ($name, $encoding) = $self->_check_sheetname($_[0], $_[1]);

# ...

my @init_data = (
$name,
$index,
$encoding,
\$self->{_activesheet},
\$self->{_firstsheet},
$self->{_url_format},
$self->{_parser},
$self->{_tempdir},
\$self->{_str_total},
\$self->{_str_unique}, # A reference ...
\$self->{_str_table},
$self->{_1904},
);

my $worksheet = Spreadsheet::WriteExcel::Worksheet->new(
@init_data # ... used here
);

The add_worksheet method passes a *reference* to
$workbook->{_str_unique} to the constructor in
Spreadsheet::WriteExcel::Worksheet to initialize
the newly created worksheet.

The debugger output is sometimes hard to read.
My guess is that you're actually seeing:

$workbook->{_str_unique} = 1;

$worksheet->{_str_unique} = \$workbook->{_str_unique};

Therefore, the latter is a reference to 1.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top