简体   繁体   中英

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

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. I cant seem to figure out how to choose based on column 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; in your perl script. 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.

And using a variable $col without defining it doesn't work either.

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};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM