[英]Perl - How to set key based on column header when converting from xlsx to perl hash
I have a xlsx that im converting into a perl hash我有一个 xlsx,我正在转换成 perl hash
Name![]() |
Type![]() |
Symbol![]() |
Colour![]() |
---|---|---|---|
JOHN![]() |
SUV![]() |
X ![]() |
R ![]() |
ROB![]() |
MPV![]() |
Y![]() |
B![]() |
JAMES![]() |
4X4 ![]() |
Y![]() |
G ![]() |
Currently, I can only set the hash superkey to the column wanted based on column array.目前,我只能根据列数组将 hash 超级键设置为想要的列。 I cant seem to figure out how to choose based on column header.
我似乎无法根据列 header 弄清楚如何选择。
use Data::Dumper;
use Text::Iconv;
my $converter = Text::Iconv->new("utf-8", "windows-1251");
use Spreadsheet::XLSX;
my $excel = Spreadsheet::XLSX->new('file.xlsx', $converter);
foreach my $sheet (@{$excel->{Worksheet}}) {
if ($sheet->{Name} eq "sheet1"){
my %data;
for my $row ( 0 .. $sheet-> {MaxRow}) {
if ($sheet->{Cells}[0][$col]->{Val} eq "Symbol"){
my $super_key = $sheet->{Cells}[$row][$col]{Val};
}
my $key = $sheet->{Cells}[$row][0]{Val};
my $value = $sheet->{Cells}[$row][2]{Val};
my $value2= $sheet->{Cells}[$row][3]{Val};
$data{$super_key}->{$key}->{$value}=${value2};
}
print Dumper \%data;
}}
The outcome i get is,我得到的结果是,
$VAR1 = {
'' => {
'JOHN' => {
'SUV' => R
I would like to have;我想拥有;
$VAR1 = {
'X' => {
'JOHN' => {
'SUV' => R
` `
You are missing use strict;
您缺少
use strict;
in your perl script.在您的 perl 脚本中。 If you had it, you would have seen your error yourself
如果你有它,你会自己看到你的错误
Defining the $super_key
with my in your If-clause, makes this variable lose scope as soon as you exit it.在你的 If 子句中用 my 定义
$super_key
,一旦你退出它,这个变量就会丢失 scope。
And using a variable $col
without defining it doesn't work either.并且在没有定义的情况下使用变量
$col
也不起作用。
Better (and probably working) is:更好的(并且可能有效)是:
for my $row ( 0 .. $sheet-> {MaxRow}) {
my $super_key;
foreach my $col (0 .. 3) {
if ($sheet->{Cells}[0][$col]->{Val} eq "Symbol"){
$super_key = $sheet->{Cells}[$row][$col]{Val};
}
}
my $key = $sheet->{Cells}[$row][0]{Val};
my $value = $sheet->{Cells}[$row][2]{Val};
my $value2= $sheet->{Cells}[$row][3]{Val};
$data{$super_key}->{$key}->{$value}=${value2};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.