简体   繁体   中英

Convert perl one liner to script

I am Vijay and i am a student and very much interested to learn perl scripting. I was learning about perl on liner. 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. 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.

$ 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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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