Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my perl hash not returning values?

Tags:

hash

perl

I'm ingesting a CSV file:

"ID","LASTNAME","FIRSTNAME","PERM_ADDR1","PERM_ADDR2","PERM_CITY","PERM_ST","PERM_ZIP","DOB","LIB_TYPE","BARCODE","EMAIL","LOCAL_ADDR1","LOCAL_ADDR2","LOCAL_CITY","LOCAL_ST","LOCAL_ZIP","CAMPUS_ADDR1","CAMPUS_ADDR2","CAMPUS_CITY","CAMPUS_ST","CAMPUS_ZIP","DEPARTMENT","MAJOR"
"123","Lastname","Firstname","123 Home St","","Home City","HS","12345-6789","0101","S","1234567890","[email protected]","123 Local St","","Local City","LS","98765-4321","123 Campus St","","Campus City","CS","54321-6789","IT",""

Using Text::CSV, I'm attempting to parse this into a hash:

my $csv = Text::CSV->new();

chomp(my $line = <READ>);
$csv->column_names(split(/,/, $line));

until (eof(READ)) {
    $line = $csv->getline_hr(*READ);
    my %linein = %$line;
    my %patron;

    $patron{'patronid'} = $linein{'ID'};
    $patron{'last'} = $linein{'LASTNAME'};
    $patron{'first'} = $linein{'FIRSTNAME'};

    print p(%linein)."\n";
    print p(%patron)."\n";
}

Using this code, the print statements at the end (using Data::Printer) return this:

{
    "BARCODE"        1234567890,
    "CAMPUS_ADDR1"   "123 Campus St",
    "CAMPUS_ADDR2"   "",
    "CAMPUS_CITY"    "Campus City",
    "CAMPUS_ST"      "CS",
    "CAMPUS_ZIP"     "54321-6789",
    "DEPARTMENT"     "IT",
    "DOB"            0101,
    "EMAIL"          "[email protected]",
    "FIRSTNAME"      "Firstname",
    "ID"             123,
    "LASTNAME"       "Lastname",
    "LIB_TYPE"       "S",
    "LOCAL_ADDR1"    "123 Local St",
    "LOCAL_ADDR2"    "",
    "LOCAL_CITY"     "Local City",
    "LOCAL_ST"       "LS",
    "LOCAL_ZIP"      "98765-4321",
    "MAJOR"          "",
    "PERM_ADDR1"     "123 Home St",
    "PERM_ADDR2"     "",
    "PERM_CITY"      "Home City",
    "PERM_ST"        "HS",
    "PERM_ZIP"       "12345-6789"
}
{
    first      undef,
    last       undef,
    patronid   undef
}

What I don't understand is why %patron is not being populated with the values from %linein. I'm wondering if this is somehow related to using Text::CSV, as I'm parsing other files elsewhere in the script and they work just fine. Those files, however, are not CSV, but rather fixed-width, so I'm parsing them manually.

like image 388
ND Geek Avatar asked Nov 30 '25 04:11

ND Geek


1 Answers

Try

 $csv->column_names(map {/"(.*)"/ and $1} split(/,/, $line))

Instead of

 $csv->column_names(split(/,/, $line));

Your CSV keys were being defined as the literal strings

 '"LASTNAME"' ,  '"FIRSTNAME"'

Instead of just

 'LASTNAME' ,  'FIRSTNAME'

Data::Printer wasn't doing too bad a job at showing you what was happening - all the keys in p(%linein) are shown as containing double quotes as part of the string, as opposed to p(%patron)

like image 92
Faiz Avatar answered Dec 02 '25 21:12

Faiz