tchike
tchike

Reputation: 164

Modify CSV file

I need to read the input CSV file, and change the header and some values as follows.

Can anybody help me to achieve this?

Input File

Level;Ref;Number;Ref Code
0;Ref1;4;16
1;Ref6;2;32
4;Ref9;7;8
6;Ref2;6;32

Output File:

Level1;Ref;Ref Code
0;Reference1;16
1;Reference6;32
4;Reference9;8
6;Reference2;32

I started with this code but I don't know how to change the header.

my $file = 'Classeur1.csv';
my $csv = Text::CSV->new( { binary => 1, eol => $/, sep_char => ';' } );
open my $io, "<", $file or die "$file: $!";

my $cols1 = $csv->column_names($csv->getline($io));
while ( my $href = $csv->getline_hr($io) ) {
    print Dumper( \$href );
}

close $io;

Dumper output

$VAR1 = { 'Number' => '4', 'Level' => '0', 'Ref Code' => '16', 'Ref' => 'Ref1' };
$VAR1 = { 'Number' => '2', 'Level' => '1', 'Ref Code' => '32', 'Ref' => 'Ref6' };
$VAR1 = { 'Number' => '7', 'Level' => '4', 'Ref Code' => '8',  'Ref' => 'Ref9' };
$VAR1 = { 'Number' => '6', 'Level' => '6', 'Ref Code' => '32', 'Ref' => 'Ref2' };

Upvotes: 1

Views: 77

Answers (1)

Borodin
Borodin

Reputation: 126722

The core Tie::File module can help you here. It allows you to access a file through a tied array, so that any changes to the array are reflected in the contents of the file

use strict;
use warnings 'all';

use Tie::File;

tie my @file, 'Tie::File', 'Classeur1.csv';

$file[0]  =~ s/Level/Level1/;
$file[$_] =~ s/Ref(\d+)/Reference$1/ for 1 .. $#file;

Upvotes: 2

Related Questions