删除打印到csv的重复条目

时间:2017-12-13 10:30:02

标签: perl csv duplicates delete-row multiple-entries

我有一个打印到csv的文件。

我已设法删除label的重复项。

我无法为service_nametotal_price重新创建此流程。

输出进入csv。

这是一项学习任务,所以我选择不使用额外的模块。

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 个答案:

答案 0 :(得分:0)

使用经过验证的模块(如Text::CSV)来创建文件。不要重新发明轮子。

答案 1 :(得分:0)

我觉得有必要清理它

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};
}

$fh更改为您的文件句柄