简体   繁体   English

将 perl one liner 转换为脚本

[英]Convert perl one liner to script

I am Vijay and i am a student and very much interested to learn perl scripting.我是 Vijay,我是一名学生,对学习 perl 脚本非常感兴趣。 I was learning about perl on liner.我在 liner 上学习 perl。 I would like to write a perl script that goes through the file line by line and compares each line with the previous line (or next line) to look for matching values in the first 3 columns.我想编写一个 perl 脚本,它逐行遍历文件并将每一行与前一行(或下一行)进行比较,以查找前 3 列中的匹配值。 Then I would like to print the values in the first three columns only once, with the fourth column value pushed on as new column.For example然后我想只打印前三列中的值一次,第四列值作为新列推送。例如

1 760605 769233 15.65  
1 760605 769233 44.11  
1 760605 769233 18.5 

Output should be输出应该是

1 760605 769233 15.65 44.11 18.5

The one liner for this is这个的一个班轮是

perl -ape '$k="@F[0..2]"; $_=" $F[3]",next if $k eq $o; $_= "\n@F";$o=$k' filename

Here i want to covert this into script and run that script.在这里,我想将其转换为脚本并运行该脚本。 If i get to know how to convert this above one liner to scripting it will be great full and i can implement the same logic to others also.如果我知道如何将上面的一个衬垫转换为脚本,它将非常完整,我也可以对其他人实施相同的逻辑。

Thank you.谢谢你。

As @Corion said, B::Deparse can help here.正如@Corion 所说, B::Deparse可以在这里提供帮助。

$ perl -MO=Deparse -ape '$k="@F[0..2]"; $_=" $F[3]",next if $k eq $o; $_= "\n@F";$o=$k'
LINE: while (defined($_ = readline ARGV)) {
    our @F = split(' ', $_, 0);
    $k = join($", @F[0..2]);
    $_ = " $F[3]", next if $k eq $o;
    $_ = "\n@F";
    $o = $k;
}
continue {
    die "-p destination: $!\n" unless print $_;
}

Cleaning that up into a pretty much equivalent script:将其清理成一个几乎等效的脚本:

#!/usr/bin/env perl
use warnings;
use strict;

my $o;
while ( my $line = <> ) {
    my @fields = split ' ', $line;
    my $k = "@fields[0..2]";
    if (defined $o && $k eq $o) {
        $line = " $fields[3]";
        next;
    }
    $line = "\n@fields";
    $o = $k;
} continue { print $line }

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

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