【问题标题】:Square and multiply two rows from two different files -Perl对来自两个不同文件的两行进行平方和相乘 -Perl
【发布时间】:2014-05-05 20:28:11
【问题描述】:

如何使用 Perl 对来自两个不同文件的两行进行平方然后相乘?
这是我的两个文件:

file1:
ID_A    AAA BBB CCC DDD FFF LLL 
ID_B    F   F   L   L   L   L   
SCORE    0.750   0.000   0.857   0.857   1.286   0.000  

file2:
ID_A    AAA BBB CCC DDD FFF LLL 
ID_B    F   F   L   L   L   L   
SCORE    1.333   0.667   1.636   0.000   1.091   0.545    

我想对两个文件的“SCORE”行中的每个值进行平方,然后将它们相乘,例如; file1 SCORE AAA to LLL 和对应的 file2 SCORE AAA to LLL:

 ie (0.750 * 0.750) * (1.333 * 1.333)
    (0.000 * 0.000) * (0.667 * 0.667)
     and so on... 

请帮我用 Perl 编写这个程序。

【问题讨论】:

    标签: perl file row multiplication


    【解决方案1】:

    记住数组中的方块,当你遇到它们时乘以下一个方块:

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    my @results;
    while (<>) {
        if (/^SCORE/) {
            my @scores = split;
            shift @scores;
            $_ *= $_ for @scores;
            if (@results) {
                @results = map { $_ * shift @scores } @results;
            } else {
                @results = @scores;
            }
        }
    }
    
    print "@results\n";
    

    保存到mutliply.pl,以multiply.pl file1 file2运行。

    输出:

    0.9995000625 0 1.965749810704 0 1.968481956676 0
    

    【讨论】:

    • 感谢代码完美运行,但是如果 file2 的行标题从“SCORE”更改为其他名称,例如“COUNT”,那么如何完成?
    猜你喜欢
    • 2020-07-26
    • 2016-12-21
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2015-05-10
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多