English 中文(简体)
您如何从电子表格中添加列, 然后在 Perl 中生成百分比?
原标题:How do you add columns from a spreadsheet and then generate percentages in Perl?

我有很多这种格式的数据

Amistad Academy District Amistad Academy    596 812 73.4
Andover School District  Andover            39  334 11.7
Ansonia School District  Ansonia High School    427 732 58.3
Ansonia School District  Ansonia Middle School  219 458 47.8
Ansonia School District  Mead School            431 642 67.1
Ansonia School District  Prendergast School 504 787 64

我需要做的是,在一连串的学校区区里,再取最后一栏,总结所有匹配区(例如,所有Ansonia地区),然后将数字除以最后一栏中的下一个至最后一栏的总和。我没有困难地将学校区分成单独的文件。这只是一个grep。然而,现在,我卡住了,认为这样做比较容易。我一直在玩各种解决方案,就像在玩游戏一样。

  1 #!/opt/local/bin/perl
  2 use strict;
  3 use warnings;
  4 use ARGV::readonly;
  5 
  6 my @data;
  7 my @headers - split  , , <>;
  8 
  9 while (<>) {
 10   my @row = split;
 11   $data[$_] += $row[$_] for (0 .. $#row);
 12 }
 13 
 14 $" = "	";
 15 print "@headers", "
";
 16 print "@data";

但无法找到计算和分割的语法 。

谢谢

问题回答

每一栏你都在弹奏,你只想总结其中两栏 否则,你几乎就在那里了

my $sum_last = 0;  # Use better name.
my $sum_penu = 0;  # Use better name.
while (<>) {
   chomp;
   my @row = split /	/;
   next if $row[0] ne  Ansonia School District ;
   $sum_last += $row[-1];
   $sum_penu += $row[-2];
}

say $sum_last / $sum_penu;

下面的程序将从文档中选择值,并将每个学校区的运行总数保留在散列中。当所有数据都读完后,散列的内容会打印出来。它从未过滤的文件中工作 - 您不必将它切换成单独的来源 。

我注意到您的数据似乎以制表符分隔,使用 split // 很重要,这样包含空间字符的字段就不会被拆分。

你不说数据意味着什么 所以我不能让代码更易读。

如有任何进一步问题,请再次询问。

use strict;
use warnings;

open my $fh,  < ,  myfile  or die $!;

scalar <$fh>; # lose header record

my %data;

while (<$fh>) {
  my @fields = split /	/;
  my $district = shift @fields;
  $data{$district}[0] += $fields[-2];
  $data{$district}[1] += $fields[-1];
}

for my $district (sort keys %data) {
  printf "%s - %f
", $district, $data{$district}[1] / $data{$district}[0];
}

<强 > 输出

Andover School District - 0.035030
Ansonia School District - 0.090569




相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签