Delete duplicate entries printing to a csv

129 Views Asked by At

I have a file that prints to a csv.

I have managed to delete duplicates for label.

I cannot recreate this process for service_name, or total_price.

The output goes into a csv.

This is a learning task so I am choosing not to use extra modules.

my @all_costs = all_shipping_costs();

foreach my $info(@all_costs) {
  foreach my $rate(@ {
    $info - > {
      'rates'
    }
  }) {}
}

my $filename = "beans.csv";
my @headings = ("Country", "Shipping Description", "Price");

#
Write out to the csv file
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";

print $fh join(",", @headings).
"\n";

my $current_label = "";
my $current_name = "";
my $current_price = "";

foreach my $info(@all_costs) {
  foreach my $rate(@ {
    $info - > {
      'rates'
    }
  }) {

    print $fh($info - > {
        'label'
      }
      ne $current_label ? "\n" : "");
    print $fh($rate - > {
        'service_name'
      }
      ne $current_name ? "" : "");
    print $fh($rate - > {
        'total_price'
      }
      ne $current_price ? "" : "");

    print $fh($info - > {
        'label'
      }
      ne $current_label ? $info - > {
        'label'
      } : "").
    ",".$rate - > {
      'service_name'
    }.
    ",".$rate - > {
      'total_price'
    }.
    "\n";

    #
    print Dumper $info;
    $current_label = $info - > {
      'label'
    };

  }
}
2

There are 2 best solutions below

0
On

Use a proven module, like Text::CSV, to create the file. Don't reinvent the wheel.

0
On

I feel compelled to clean this up

use strict;
use warnings;
use feature 'say';

# it seems like your data structure is something like this:
my @all_costs = (
    {
        label => 'label1',
        rate => {
            service_name => 'name1',
            total_price => 42
        }
    },
    {
        label => 'label2',
        rate => {
            service_name => 'name2',
            total_price => 43
        }
    }
);

my $fh = *STDOUT;
say {$fh} join ',', 'Country', 'Shipping Description', 'Price';
for my $info (@all_costs) {
    say {$fh} join ',', $info->{label}, $info->{rate}->{service_name}, $info->{rate}->{total_price};
}

change $fh to your filehandle