0

I'm no expert at Perl, wondering why the first way of obtaining numSheets is okay, while the following way isn't:

use Spreadsheet::Read;
my $spreadsheet = ReadData("blah.xls");
my $n1 = $spreadsheet->[1]{sheets};     # okay
my %sh = %spreadsheet->[1];             # bad
my $n2 = $sh{label};    

The next to last line gives the error

Global symbol "%spreadsheet" requires explicit package name at newexcel_display.pl line xxx

I'm pretty sure I have the right sigils; if I experiment I can only get different errors. I know spreadsheet is a reference to an array not directly an array. I don't know about the hash for the metadata or individual sheets, but experimenting with different assumptions leads nowhere (at least with my modest perl skill.)

My reference on Spreadsheet::Read workings is http://search.cpan.org/perldoc?Spreadsheet::Read If there are good examples somewhere online that show how to properly use Spreadsheet, I'd like to know where they are.

DarenW
  • 16,549
  • 7
  • 63
  • 102

1 Answers1

3

It's not okay because it's not valid Perl syntax. The why is because that's not how Larry defined his language.

The sigils in front of variables tell you what you are trying to do, not what sort of variable it is. A $ means single item, as in $scalar but also single element accesses to aggregates such as $array[0] and $hash{$key}. Don't use the sigils to coerce types. Perl 5 doesn't do that.

In your case, $spreadsheet is an array reference. The %spreadsheet variable, which is a named hash, is a completely separate variable unrelated to all other variables with the same identifier. $foo, @foo, and %foo come from different namespaces. Since you haven't declared a %spreadsheet, strict throws the error that you see.

It looks like you want to get a hash reference from $spreadsheet->[1]. All references are scalars, so you want to assign to a scalar:

 my $hash_ref = $spreadsheet->[1];

Once you have the hash reference in the scalar, you dereference it to get its values:

 my $n2 = $hash_ref->{sheets};

This is the stuff we cover in the first part of Intermediate Perl.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
  • It works, and after re-reading stuff I had already read in recent days, this now makes sense (kinda). Still, quantum field theory seems _so_ much easier than Perl... – DarenW Apr 05 '12 at 22:13