in reply to Re: csv to hash table
in thread csv to hash table

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;

Replies are listed 'Best First'.
Re^3: csv to hash table
by kcott (Archbishop) on Nov 19, 2013 at 05:46 UTC

    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

      Why => in split /$field_separator/ => $record? To my eye that says paired item, but there it's just a plain ol' comma and would be clearer as:

      my @fields = split /$field_separator/, $record;

      Personally I prefer making the record variable explicit, but I'd write the while expression as:

      while (defined (my $record = <$filehandle>)) {

      which is a closer match to the magic you get with while (<$filehandle>) {.

      True laziness is hard work
        "Why => in split /$field_separator/ => $record?"

        Beyond being a preferred style, it has no particular significance.

        "To my eye that says paired item, but there it's just a plain ol' comma and would be clearer as: ..."

        I really can't believe you're having any difficulty with the clarity of that code; however, if you are, think of it in terms of this pairing:

        how to split => what to split

        With regards to the while condition, my intention was to point out the confusion between the filehandle and the record. I thought I'd made that fairly clear with my opening sentence. I didn't consider a more in-depth discussion of how <$filehandle> works to be useful or helpful in this context.

        [To waytoperl: If you're wondering about this use of defined, it's explained in more detail in perlop: I/O Operators.]

        -- Ken