Domanda

I have a subroutine in a Perl script that opens a csv file and reads the values into a hash table. The script is currently running without a problem on a Windows 2003 server. I am trying to get the script running on a Windows 2008 R2 server. When I run the script on the R2, it fails with the following error: Can't locate object method "getLine" via package "C:\file\test.csv" (perhaps you forgot to load "C:\file\test.csv)

I am running the script from the command line in the directory containing both the Perl script and the csv file. I am able to use the move() function to rename the csv file. Obviously, the csv file is being found, it's just not being read.

sub csv_file_hashref {
   my ($filename) = @_;
   my $csv_fh = IO::File->new($filename, 'r');
   my $csv = Text::CSV_XS->new ();
   my %output_hash;
   while(my $colref = $csv->getline ($filename))
   {
      $output_hash{shift @{$colref}} = $colref;
   }

   return \%output_hash;                        # return a reference to the hash
}

I have confirmed that the correct file name with full directory is in $filename. I've alos ensured that the IO::File module is installed. Why won't this code open the csv file?

Thanks, Alex

È stato utile?

Soluzione

getline takes a filehandle as an argument, but you're passing the file name. Change

while(my $colref = $csv->getline ($filename))

to

while(my $colref = $csv->getline ($csv_fh))

Altri suggerimenti

The IO::File module is sometimes helpful if you want to treat your file handle as an object, but it is best in general to use Perl's native open operator.

As has been said, the problem is that you aren't using your file handle after opening the file: you should be passing it to Text::CSV's getline method.

In addition, you are setting the value of the hash elements to array reference $colref instead of the value of the second element of the array it refers to.

Here's a tidied-up version of your subroutine with these points fixed.

sub csv_file_hashref {
   my ($filename) = @_;

   open my $csv_fh, '<', $filename or die qq{Unable to open "$filename" for input: $!};
   my $csv = Text::CSV_XS->new;
   my %output_hash;

   while (my $row = $csv->getline($csv_fh)) {
      $output_hash{$row->[0]} = $row->[1];
   }

   return \%output_hash;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top