Newbie
Newbie

Reputation: 2708

Ignore empty lines in a CSV file using Perl

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.

Upvotes: 2

Views: 2325

Answers (4)

AKHolland
AKHolland

Reputation: 4445

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 };
    ...
}

Upvotes: 0

Kenosis
Kenosis

Reputation: 6204

You can do the following to skip empty lines:

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

Upvotes: 0

Zach Leighton
Zach Leighton

Reputation: 1941

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;
}

Upvotes: 0

Gabs00
Gabs00

Reputation: 1877

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.

Upvotes: 1

Related Questions