电子表格中的 Perl 哈希严格引用错误

Perl hash strict ref error in spreadsheet

下面是perl代码

1
2
3
4
5
6
7
8
9
10
11
use Spreadsheet::WriteExcel;

my $workbook = new Spreadsheet::WriteExcel( 'one_worksheet.csv' );

my ${path_1} = $workbook->add_worksheet('Max Input');
my ${path_2} = $workbook->add_worksheet('Min Input');

foreach (keys %max_hash ) {
    ${$_}->write(0, $column,"$max_hash{$_}" );
    $column = $column + 1;
}

我收到此错误

1
"Can't use string ("path_1") as a SCALAR ref while"strict refs" in use".

%max_hash 有键 path_1path_2.

解决办法是什么?


语法 my ${path_1} 是不寻常的,但实际上不是问题。打开 use warnings 后,您将收到一条警告消息:

Ambiguous use of ${path_1} resolved to $path_1

最好用 my $path_1.

替换它

你的实际问题是这一行:

1
${$_}->write(0,$column,"$max_hash{$_}");

您正在尝试使用称为"符号引用"的东西(也称为"使用变量作为变量的名称")。由于各种原因,它们是一个非常糟糕的主意 - 这就是 use strict 阻止你这样做的原因。

最好将工作表存储在哈希中。

1
2
3
4
5
6
7
8
9
10
11
use Spreadsheet::WriteExcel;

#"Class->new()" is far better than"new Class"
my $workbook = Spreadsheet::WriteExcel->( 'one_worksheet.csv' );
my %worksheets;
$worksheets{path_1} = $workbook->add_worksheet('Max Input');
$worksheets{path_2} = $workbook->add_worksheet('Min Input');
foreach(keys %max_hash) {
    $worksheets{$_}->write(0, $column, $max_hash{$_});
    $column = $column + 1;
}

声明变量时不要使用花括号。用途:

1
my $path_1 = $workbook->add_worksheet('Max Input');

${something} 语法意味着取消引用,因此 perl 将 something 视为引用。此外,它与 my.

一起使用是错误的