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

Okay, here is my text file...
"Incoming Data"|09/12/2001|"Another Test"| "LIne 2"|Outline3|09/02/2001
How do I go about reading this into a hash? The | character is required to read in this file as this is what is being used to seperate the fields out... Please help if you can. thanks dez L

Replies are listed 'Best First'.
Re: Delimmeted Text Files..
by Hofmator (Curate) on Oct 15, 2001 at 20:16 UTC

    I'd suggest using Text::CSV_XS for the splitting of the line and after that the hash should be easy to build. Post some code to show your problems ...

    -- Hofmator

Re: Delimmeted Text Files..
by MZSanford (Curate) on Oct 15, 2001 at 20:19 UTC
    To give a good answer, i would need to know which fields you expect to be unique, because otherwise, the act of placing the data in a hash will mangle it. Assuming you want something line field 1 as a key, and all other fields as a value, i might suggest :
    while (my $line = <FH>) { my @a = split(/\|/,$line); my $b = shift(@a); $HASH{$b} = \@a; } print "LIne 2 : ",join(',',$HASH{'LIne 2'}),"\n";

    The requirements change because they don't know what they want, or how much they own you.
Re: Delimmeted Text Files..
by Fletch (Bishop) on Oct 15, 2001 at 20:23 UTC

    Of course if | will never occur inside of a field you can just use split( /\|/, $_ ) instead of Text::CSV_XS. But if you need something fancier that deals with quotes and escaped seperators, then the CSV module is probably your best bet.

Re: Delimmeted Text Files..
by TGI (Parson) on Oct 15, 2001 at 20:26 UTC

    What do you want the keys to be? What do you want to store in the hash? A list reference (see perlref for more info on references)? One value from the line? You'll need to be a bit more specific.

    What you want to do is open a file handle, and split each line into an array. Then you munge the data into whatever structure you want. I'll post some code if you explain what you're looking for.


    TGI says moo

Re: Delimmeted Text Files..
by herveus (Prior) on Oct 15, 2001 at 20:21 UTC
    Howdy!

    -- for saying not nearly enough to permit pertinent answer.

    Which part of the input data is the hash key and which is the data? I see three fields on each line; are both to be stored under the same hash key?

    One can readily split on /\|/ (*run! run! Leaning Toothpick Syndrome!*) but you give no help with how to process the fields.

    yours,
    Michael