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

Hi Monks,

I'm trying to read a datafile and append data onto a specific line as indexed/identified by the first word.

The data file is in this format

name,success1,description1,success2,description2,...

eg:
dog,yes,string1,yes,string2 cat,no,string3 mouse,no,string4,no,string5 horse ferret
My attempt at doing this is below. Apart from it not working, it seems to hang on the 'split' line
#!/bin/perl use strict; use warnings; use Data::Dumper; my $name="mouse"; open (FH, "datafile.txt")||die "cannot open file"; while ( <FH> ) { next unless s/^(.*?):\s*//; $HoA{$1} = [ split /,/ ]; } print Dumper(%HoA); my $success="yes"; my $description="new string"; push @{ $HoA{$name} }, $success, $description; for $venue ( keys %HoA ) { print FH "$venue @{ $HoA{$venue} }\n"; }
Can any one help and show me the correct way, or even a better way, of doing this??

Replies are listed 'Best First'.
Re: Trying to read a file into a Hash of Arrays
by Athanasius (Archbishop) on Feb 20, 2015 at 04:46 UTC
Re: Trying to read a file into a Hash of Arrays
by vinoth.ree (Monsignor) on Feb 20, 2015 at 04:46 UTC

    You have opened a file for reading input but, you are trying to write into it.

    Filehandle FH opened only for input at pl.pl line 18, <FH> line 5

    Open the file in read/write mode as below,

    #!/bin/perl use strict; use warnings; use Data::Dumper; my $name="mouse"; pen (FH, "+<","datafile.txt")||die "cannot open file"; my (%HoA,$venue); while ( <FH> ) { next unless s/^(.*?):\s*//; $HoA{$1} = [ split /,/ ]; } print Dumper(%HoA); my $success="yes"; my $description="new string"; push @{ $HoA{$name} }, $success, $description; for $venue ( keys %HoA ) { print FH "$venue @{ $HoA{$venue} }\n"; }
    Update:

    ++Athanasius,Missed use strict; part.


    All is well. I learn by answering your questions...
Re: Trying to read a file into a Hash of Arrays
by LanX (Saint) on Feb 20, 2015 at 04:46 UTC
    > next unless s/^(.*?):\s*//;

    Please explain what this line is supposed to do in "your attempt".

    Cheers Rolf

    PS: Je suis Charlie!

Re: Trying to read a file into a Hash of Arrays
by sandy105 (Scribe) on Feb 20, 2015 at 10:42 UTC

    yes that is correct it will skip all lines because your test data signature does not have : or else your actual test data looks like "dog: string1,str2...."

      > actual test data ..

      Well the actual test data included $venue as keys...

      Most likely C&P homework...

      Cheers Rolf

      PS: Je suis Charlie!