Ignore blank 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.


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 ] );

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.

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

unless(defined($id) && defined($flop) && defined($ub)){

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){

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.