Lady_Aleena has asked for the wisdom of the Perl Monks concerning the following question:
Hello. In my effort to improve my perl writing, I was going to take some of my own advice and stop trying to find reasons to not use something. With that in mind, I finally decided to look into Text_CSV_XS to replace my hand rolled flat file processor. I gravitated right to the function csv in the module as it looked easier to use. However, I came upon a problem. In the POD it says that when key is set, headers is set to auto, so the headers I set would not work.
So, other than going through every flat file I have and adding the headers, can anyone think of a way to work around? I have so very many flat files and could possibly miss a few, so adding headers in now would be problematic.
What I want is a hash of hashes with the first item on each line to be the key to the hash along with being a named value in the hash.
Is there maybe someone who would hold my hand as I try to work through the method in Text::CSV_XS?
My data
Crystal Skull|Stargate SG-1, Crystal Skull;The Librarian: Return to Ki +ng Soloman's Mines;Indiana Jones and the Kingdom of the Crystal Skull Spear of Destiny|The Librarian: Quest for the Spear;Hellboy;Constantin +e Book or Key of Soloman|The Librarian: Return to King Soloman's Mines;S +eason of the Witch Necronomicon|H.P. Lovecraft
My code
#!/usr/bin/perl use strict; use warnings; use Text::CSV_XS qw(csv); my $file = '/home/me/Documents/www/files/data/Miscellany/Magic_items.t +xt'; open(my $fh, '<', $file) || die "Can't open $file $!"; my $list = csv ( in => $file, sep_char => '|', headers => ['item', 'seen in'], key => ['item'], ); use Data::Dumper; print Dumper $list;
My result
Use of uninitialized value in anonymous hash ({}) at /home/me/perl5/li +b/perl5/x86_64-linux-gnu-thread-multi/Text/CSV_XS.pm line 1223, <$fh> + line 4. Use of uninitialized value in anonymous hash ({}) at /home/me/perl5/li +b/perl5/x86_64-linux-gnu-thread-multi/Text/CSV_XS.pm line 1223, <$fh> + line 4. Use of uninitialized value in anonymous hash ({}) at /home/me/perl5/li +b/perl5/x86_64-linux-gnu-thread-multi/Text/CSV_XS.pm line 1223, <$fh> + line 4. Use of uninitialized value in anonymous hash ({}) at /home/me/perl5/li +b/perl5/x86_64-linux-gnu-thread-multi/Text/CSV_XS.pm line 1223, <$fh> + line 4. $VAR1 = { '' => { 'seen in' => 'H.P. Lovecraft', 'item' => 'Necronomicon' } };
Update: This is as far as I have gotten with the method version.
$csv = Text::CSV_XS->new ({ sep_char => '|', quote_char => undef, blank_is_undef => 1, empty_is_undef => 1, allow_whitespace => 1, });
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Text::CSV_XS function does not accept headers and key together
by Tux (Canon) on Jun 07, 2017 at 09:15 UTC |