Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

csv to hash table

by waytoperl (Beadle)
on Nov 19, 2013 at 04:41 UTC ( [id://1063263]=perlquestion: print w/replies, xml ) Need Help??

waytoperl has asked for the wisdom of the Perl Monks concerning the following question:

Need to create a hash table from csv file. Starting from sample code's, I'm getting error. I don't know do i need to use hash_ref to recognize(add/modify) hash table. Hash table should contain contents of Column1 and Column5 from CSV file. Hash $keys need to be Column5 and corresponding $values to be Column1. Later, I'll refer/replace Column1 to edit other task. Please help me how to solve these task! Thanks

line 1 table description,,,,,,,, line 2 few more file describtion,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, Column_1,Column_2,,,,Column_3,Column_4,Column_5, Name11,In,,,,DATA13,DATA14,Id11, Name21,Out,,,,DATA23,DATA24,Id11, Name31,In,,,,DATA33,DATA34,Id22, Name41,In,,,,DATA43,DATA44,Id22, ,,,,, ,,,,, ,,,,,
sub mainCSV { open (my $inputfile1, '<', "$inputfile") or die "Unable to open $input +file1: $!"; my %hash; while (<$inputfile1>) { $inputfile1 =~ s/\s*\z//; my @arrayfile1 = split /,/, $inputfile1; my $keyfile1 = shift @arrayfile1; $hash{$keyfile1} = \@arrayfile1; } print %hash; close $inputfile1; }

Replies are listed 'Best First'.
Re: csv to hash table
by BrowserUk (Patriarch) on Nov 19, 2013 at 05:23 UTC
     $inputfile1 =~ s/\s*\z//;

    $inputfile1 is your filehandle, but you are editing that filehandle and thus corrupting it. Try:

    sub mainCSV { open (my $inputfile1, '<', "$inputfile") or die "Unable to open $i +nputfile1: $!"; my %hash; while( my $line = <$inputfile1> ) { $line =~ s/\s*\z//; my @arrayfile1 = split /,/, $line; my $keyfile1 = shift @arrayfile1; $hash{$keyfile1} = \@arrayfile1; } print %hash; close $inputfile1; }

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      Thanks for responding BrowerUk. After updating, i have error of uninitiated value. I think it might be because of input CVS file have initial few lines of dummy values Any way I can create hash table to start from starting at particular line in CSV file.

      Use of uninitialized value in hash element at perl_program.pl line 67, <$inputfile1> line 3 (#1) (W uninitialized) An undefined value was used as if it were already defined. It was interpreted as a "" or a 0, but maybe it was a mistake. To suppress this warning assign a defined value to your variables. To help you figure out what was undefined, perl tells you what operation you used the undefined value in. Note, however, that perl optimizes your program and the operation displayed in the warning may not necessarily appear literally in your program. For example, "that $foo" is usually optimized into "that " . $foo, and the warning will refer to the concatenation (.) operator, even though there is no . in your program. Use of uninitialized value in hash element at perl_program.pl line xx, <$inputfile1> line 4 (#1) Use of uninitialized value in hash element at perl_program.pl line xx, <$inputfile1> line 5 (#1) Use of uninitialized value in hash element at perl_program.pl line xx, <$inputfile1> line 6 (#1) Use of uninitialized value in hash element at perl_program.pl line xx, <$inputfile1> line 7 (#1)

        Any way I can create hash table to start from starting at particular line in CSV file.

        Read past the lines you want to skip before entering your while loop.

        (Ps. If you can't work out how to do that for yourself, you might consider employing someone to write this code for you.)


        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
Re: csv to hash table
by kcott (Archbishop) on Nov 19, 2013 at 05:07 UTC

    G'day waytoperl,

    Firstly, for manipulation of CSV files in Perl, you should be using one of the Text::CSV family of modules. There's all sorts of gotchas with CSV files, including field separators embedded within the field data, various quoting mechanisms and so on. All this has already been coded in these modules, so there's really no point in reinventing this particular wheel.

    While I haven't used it myself, it looks like "Text::CSV::Hashify - Turn a CSV file into a Perl hash", which is built upon Text::CSV, might handle your specific requirements in this instance.

    [Aside: Your OP mentions an error: you don't show the error nor do you provide runnable code that we could use to reproduce it. For future reference, in order to help us help you, please follow the guidelines in "How do I post a question effectively?".]

    -- Ken

Re: csv to hash table
by 2teez (Vicar) on Nov 19, 2013 at 05:01 UTC

    Hi waytoperl,
    ..I'm getting error..
    What error or (type) are you getting?
    Use either Text::CSV or Text::CSV_XS for your CSV file, instead of split function. Then the rest is just manipulation of dataset.

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me

      perl perl_program.pl readline() on unopened filehandle at perl_program.pl line xx (#1) (W unopened) An I/O operation was attempted on a filehandle that was never initialized. You need to do an open(), a sysopen(), or a socket() call, or call a constructor from the FileHandle package. GLOB(0x5fc7210)ARRAY(0x603a130)

      line xx: is $hash{$keyfile1} = \@arrayfile1;

        You're confusing the filehandle with the record being read.

        Using more code than is really necessary to demonstrate the point:

        open my $filehandle, ... while (my $record = <$filehandle>) { chomp $record; # Remove the newline # Do stuff with the record text, e.g. my @fields = split /$field_separator/ => $record; ... }

        That would normally be coded more succinctly as:

        open my $filehandle, ... while (<$filehandle>) { chomp; # Remove the newline # Do stuff with the record text, e.g. my @fields = split /$field_separator/; ... }

        In the second code fragment, all instances of $record (from the first fragment) are now $_, which (being the default for chomp, split, and many other functions) can be omitted.

        And, just in case it wasn't obvious, that was for general enlightenment, not a recommendation to attempt your own version of Text::CSV. :-)

        -- Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1063263]
Approved by kcott
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (2)
As of 2024-04-26 01:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found