swagdaddy
swagdaddy

Reputation: 1

Reading a CSV file and writing to a CSV file

use Text::CSV;
$csv = Text::CSV->new;
open(HIGH, "+>Hardtest.csv") || die "Cannot open ticket $!\n"; #reads the high file
while(<HIGH>)
{
    print "Printing High Priority Tickets ...\n";
    sleep(1);
    print <HIGH>;
}
close(HIGH);

here is my code, i am trying to read a csv and write to it, however i cant seem to read the CSV file, help would be appreciated, thanks!

Upvotes: 0

Views: 92

Answers (2)

J Singh
J Singh

Reputation: 162

I've modified your code a bit:

#!/usr/bin/perl -w
use strict;
use Text::CSV;

my $csv = Text::CSV->new;
open(HIGH, "+<Hardtest.csv") || die "Cannot open ticket $!\n"; #reads the high file
while(<HIGH>)
{
    print "Printing High Priority Tickets ...\n";
    print $_;
    sleep(1);
}
print HIGH "9,10,11,12\n";
close(HIGH);

Let me explain: 1. "+>" will open the file in read/write mode, BUT will also overwrite the existing file. Hence, In your code, while loop is never entered. I've changed that to "+<" which means read/write in append mode. 2. Second last statement, in above code, will append new content to the CSV file.

Upvotes: 0

jimtut
jimtut

Reputation: 2393

OK, lots of things here.

  1. Always use strict and use warnings.
  2. You're opening the CSV file write mode (append mode?). Don't do that, if you're just reading from it.
  3. Don't use || die, use or die.
  4. Finally, don't print <HIGH>, instead print $_.

Upvotes: 2

Related Questions