Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 如何使用Perl将数据文件的a列除以B列_Linux_Perl_Command - Fatal编程技术网

Linux 如何使用Perl将数据文件的a列除以B列

Linux 如何使用Perl将数据文件的a列除以B列,linux,perl,command,Linux,Perl,Command,我得到了一个文本文件,其中包含按列排序的一大堆数据。每列都是 用逗号分隔 如何将一列除以另一列以打印输出答案?我现在正在使用Perl,所以必须用Perl完成。我怎么能这样做 这就是我到目前为止所做的: #!/usr/bin/perl open (FILE, 'census2008.txt'); while (<FILE>) { chomp; ($sumlev, $stname,$ctyname,$popestimate2008,$births2008,$d

我得到了一个文本文件,其中包含按列排序的一大堆数据。每列都是 用逗号分隔

如何将一列除以另一列以打印输出答案?我现在正在使用Perl,所以必须用Perl完成。我怎么能这样做

这就是我到目前为止所做的:

 #!/usr/bin/perl

 open (FILE, 'census2008.txt');
 while (<FILE>) {
     chomp;
     ($sumlev, $stname,$ctyname,$popestimate2008,$births2008,$deaths2008) = split(",");
 }
 close (FILE);
 exit;

有几种选择:

逐行读取文件,将“,”上的列和相关列分开。不要忘记处理“除以零”错误

执行与单衬套相同的操作:

$ perl -F/,/ -lane 'print( $F[1] == 0 ? "" : $F[3]/$F[1] )' file.txt
利用现成的CPAN模块,如

当然,还有更多的非正统/疯狂/难以言喻的替代品™, 因此,我们可以:

使用正则表达式解析出相关列并划分匹配项:

if (/^\d*,(\d+),\d*,(\d+)/) { say $2/$1 if $2 != 0; }
使用s///e执行此操作:

让shell通过反勾号执行脏工作:

sub print_divide { say `cat file.txt | some_command_line_command` }

如果您有固定宽度的数据列,您可以使用“解包”方式,如下所示:

#!/usr/bin/env perl
use strict;
use warnings;
while (<DATA>) {
    chomp;
    my ($sumlev,$stname,$ctyname,$popest,$births,$deaths)
        = unpack("A2xA10xA15xA7xA5xA5");
    printf "%-15s %4.2f\n", $ctyname, $births/$deaths;
}
__DATA__
10,Main      ,My City        ,  10000,  200,  150
12,Poplar    ,Somewhere      ,   3000,   90,  100
13,Maple     ,Your Place     ,   9123,  100,   90

你刚把值做成数组了吗?我只是想知道。你能解释一下你的分裂函数吗?我是新手,不知道它在说什么。
sub print_divide { say `cat file.txt | some_command_line_command` }
#!/usr/bin/env perl
use strict;
use warnings;
while (<DATA>) {
    chomp;
    my ($sumlev,$stname,$ctyname,$popest,$births,$deaths)
        = unpack("A2xA10xA15xA7xA5xA5");
    printf "%-15s %4.2f\n", $ctyname, $births/$deaths;
}
__DATA__
10,Main      ,My City        ,  10000,  200,  150
12,Poplar    ,Somewhere      ,   3000,   90,  100
13,Maple     ,Your Place     ,   9123,  100,   90