RookiePerl has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to assign an Excel spreadsheet to a global variable, and I am finding this does not work. If I assign it to a local variable (using the "my" prefix), it works just fine. Am I missing something?

use Spreadsheet::Write; $h=Spreadsheet::Write->new( file => 'sample.xls', format => 'xls', sheet => 'test'); $h->addrow('Hello',{ content => 'there', font_weight => 'bold', font_color => 'red', font_face => 'Times New Roman', font_size => 10, font_style => 'italic', });

Replies are listed 'Best First'.
Re: Global Variable for Worksheet?
by moritz (Cardinal) on Mar 21, 2012 at 15:41 UTC

    The difference is that if the object is in a lexical variable, the DESTROY method is called when it goes out of scope (and no other refereeneces to it exist). This happens at the end of the program. It seems that Spreadsheet::Write uses that to actually write its output file.

    Other methods to trigger it is to remove all references to the object. For example you could add $h = undef at the end of your program.

    But do consider using lexical variables wherever possible, they usually make life easier.

Re: Global Variable for Worksheet?
by jmcnamara (Monsignor) on Mar 21, 2012 at 15:55 UTC

    moritz is correct about the object scope and destruction. You can force a manual destruction by calling the undocumented Spreadsheet::Write::close() method at the end of your program:

    ... $h->close();

    --
    John.