简体   繁体   English

如何使用perl从文本文件中选择列

[英]how do you select column from a text file using perl

I want to subtract values in one column from another column and add the differences.How do I do this in perl? 我想从另一列中减去一列中的值并添加差异。如何在perl中做到这一点? I am new to perl.Hence I am unable to figure out how to go about it. 我是perl的新手,因此我不知道该怎么做。 Kindly help me. 请帮助我。

The first thing is to separate the data into columns. 第一件事是将数据分成几列。 In this case, the columns are separated by a space. 在这种情况下,列之间用空格隔开。 split(/ /) will return a list of the columns. split(/ /)将返回列的列表。

To subtract one from the other, its pulling the values out of the the list and subtracting them. 要从另一个中减去一个,它将值从列表中拉出并减去。

At the end, you add the difference to the running sum and then loop over the data. 最后,将差值添加到运行总和中,然后遍历数据。

#!/usr/bin/perl

use strict;

my $sum = 0;

while(<DATA>) {
    my @vals = split(/ /);
    my $diff = $vals[1] - $vals[0];
    $sum += $diff;
}

print $sum,"\n";

__DATA__
1 3
3 5
5 7

This will print out 6 --- (3 - 1) + (5 - 3) + (7 - 5) 这将打印出6 ---(3-1)+(5-3)+(7-5)

仅供参考,如果您结合使用自动拆分( -a ),循环( n )和命令行程序( -e )参数(请参阅perlrun ),则可以将其缩短为单行格式 ,就像awk一样:

perl -ane "$sum += $F[1] - $F[0]; END { print $sum }" filename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM