#!/usr/bin/perl use strict; use warnings; use Text::CSV; my $csv = Text::CSV->new({ binary => 1, auto_diag => 1, eol => $/ }); open(my $input, '<', 'output.csv') or die "Could not open output.csv: $!"; open(my $temp_output, '>', 'temp_output.csv') or die "Could not open temp_output.csv: $!"; # This will hold all the numbers from the combined Clean and Cleaned_FDNC my %combined_numbers; my $header = $csv->getline($input); # Read the header push @$header, 'DNC'; # Add the DNC column to header $csv->print($temp_output, $header); # Print the header to output # Process the header row my ($all_col, $clean_col, $fdnc_col, $invalid_col, $cleaned_all_col, $cleaned_fdnc_col) = @$header; my $dnc_col = ''; while (my $row = $csv->getline($input)) { next unless $row; # Skip undefined rows # Skip any row that matches the header pattern next if $row->[0] =~ /^all$/i && $row->[1] =~ /^clean$/i && $row->[2] =~ /^fdnc$/i; my ($all, $clean, $fdnc, $invalid, $cleaned_all, $cleaned_fdnc) = @$row; # Record the numbers from Clean and Cleaned_FDNC columns $combined_numbers{$clean} = 1; $combined_numbers{$cleaned_fdnc} = 1; # If the number from Cleaned_All is not in the combined numbers of Clean and Cleaned_FDNC, then it's DNC if (!exists $combined_numbers{$cleaned_all}) { $dnc_col = $cleaned_all; } # Print the data with DNC to the new output file $csv->print($temp_output, [$all, $clean, $fdnc, $invalid, $cleaned_all, $cleaned_fdnc, $dnc_col]); } close($input); close($temp_output); # Rename the temporary file to output.csv rename("temp_output.csv", "output2.csv");