user3269877
user3269877

Reputation: 13

Reading a single column from csv using perl

file has data like this:

S_No        S_Name          Acc_Num     Total_Amount
1            Larry            1521          18000           

To read a column from csv for this purpose I wrote this script:

#!/usr/bin/perl -w
use strict;
use warnings;

use Text::CSV;
my$column_separator = qr/,/;
my $column_number = "3";
my$file = "/home/Admin/Documents/new (copy).csv";
open(my$FILE,">>","$file") or die "$!";
while (<$FILE>){
  my @columns = split(/$column_separator/);
  print $columns[$column_number] ,"\n";
}
close $FILE;

But this script is throwing an error.

Use of uninitialized value in print at another.pl line 12, <$FILE> line from 1 to 11..

how to resolve this error?

Upvotes: 0

Views: 2124

Answers (1)

simbabque
simbabque

Reputation: 54381

The error message means that the column is empty. That's why it is undefined. You need to add a check and handle the case that it is empty. You can do that in two ways:

  • add a condition and not output empty columns at all

    print $columns[$column_number], "\n" if $columns[$column_number];
    
  • output an empty line if the value is not defined

    print( ( $columns[$column_number] // q{} ), "\n");
    

Here are some more comments: You are useing Text::CSV, but then you are not using it to read anything.

What you are instead doing is reading the file line by line, but there are a few things that you need to add and change:

  • change the mode of your open call from >> to < because >> means append, but you want to read
  • chomp the input to remove trailing newlines

All of this results in the following code.

open(my $FILE,">>","$file") or die "$!";
while (<$FILE>) {
  chomp;
  my @columns = split(/$column_separator/);
  print ( $columns[$column_number] // q{} ), "\n";
}

You should also read up on Text::CSV and learn to use it as it will help with a lot of common pitfalls for CSV files.

Upvotes: 1

Related Questions