2

I have to read a CSV file, abc.csv, select a few fields from them and form a new CSV file, def.csv.

Below is my code. I am trying to ignore empty lines from abc.csv.

genNewCsv();

sub genNewCsv {
    my $csv = Text::CSV->new();
    my $aCsv = "abc.csv"
    my $mCsv = "def.csv";
    my $fh = FileHandle->new( $aCsv, "r" );
    my $nf = FileHandle->new( $mCsv, "w" );

    $csv->print( $nf, [ "id", "flops""ub" ] );
    while ( my $row = $csv->getline($fh) ) {

        my $id = $row->[0];

        my $flops = $row->[2];
        next if ( $id =~ /^\s+$/ );    #Ignore empty lines

        my $ub = "TRUE";
        $csv->print( $nf, [ $id, $flops, $ub ] );
    }
    $nf->close();
    $fh->close();
}

But I get the following error:

Use of uninitialized value $flops in pattern match (m//)

How do I ignore the empty lines in the CSV file?

I have used Stack Overflow question Remove empty lines and space with Perl, but it didn't help.

3
  • fyi, you appear to be missing a comma between "flops" and "ub" Commented Jan 6, 2014 at 6:26
  • Move the 'next if ...' one line up, because you Cañons access elements if the line is . Commented Jan 6, 2014 at 6:54
  • Adding to @Gabs00, you have more syntax errors: my $aCsv = "abc.csv" is missing a ;. Copy-Paste mistake? Commented Jan 6, 2014 at 7:34

4 Answers 4

1

You can skip the entire row if any fields are empty:

unless(defined($id) && defined($flop) && defined($ub)){
    next;
}

You tested if $id was empty, but not $flops, which is why you got the error.

You should also be able to do

unless($id && $flop && $ub){
   next;
}

There, an empty string would evaluate to false.

Edit: Now that I think about it, what do you mean by ignore lines that aren't there?

You can also do this

my $id = $row[0] || 'No Val' #Where no value is anything you want to signify it was empty

This will show a default value for the the variable, if the first value evaluated to false.

Sign up to request clarification or add additional context in comments.

Comments

0

Run this on your file first to get non-empty lines

sub removeblanks {
  my @lines = (); 
  while(@_) {
        push @lines, $_ unless( $_ =~ /^\s*$/ ); #add any other conditions here
  }
  return \@lines;
}

Comments

0

You can do the following to skip empty lines:

while (my $row = $csv->getline($fh)){
    next unless grep $_, @$row;
    ...

Comments

0

You could use List::MoreUtils to check if any of the fields are defined:

use List::MoreUtils qw(any);
while(my $row = ...) {
    next unless any { defined } @{ $row };
    ...
}

1 Comment

This didn't work for me. I had to use any { $_ eq '' }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.