Weiqing Wang
Weiqing Wang

Reputation: 79

What does this code do in perl

The input to perl is like this:

ID NALT NMIN NHET NVAR SING TITV QUAL DP G|DP NRG|DP
PT-1RTW 1 1 1 4573 1 NA 919.41 376548 23.469 58
PT-1RTX 0 0 0 4566 0 NA NA NA 34.5866 NA
PT-1RTY 1 1 1 4592 1 NA 195.49 189549 24.0416 18
PT-1RTZ 0 0 0 4616 0 NA NA NA 44.1474 NA
PT-1RU1 0 0 0 4609 0 NA NA NA 28.2893 NA
PT-1RU2 2 2 2 4568 2 0 575.41 330262 28.2108 49
PT-1RU3 0 0 0 4617 0 NA NA NA 35.9204 NA
PT-1RU4 0 0 0 4615 0 NA NA NA 30.5878 NA
PT-1RU5 0 0 0 4591 0 NA NA NA 26.2729 NA

This is the code:

perl -pe 'if($.==1){@L=split;foreach(@L){$_="SING.$_";}$_="@L\n"}'

I sort of guessed it is processing the first line to add SING to each word. but what does the last part $_="@L\n" do? without this, this code doesn't work.

Upvotes: 0

Views: 108

Answers (2)

AnFi
AnFi

Reputation: 10903

-p command line switch makes perl process input (or files listed at command line) "line by line" and print processed lines. The line content is stored in $_ variable. $_="@L\n" assign new value to $_ before it is printed.

Shorter version: perl -pe 'if($.==1){s/(^| )/$1SING./g}'


Deparsed (more readable) one-liner above:

perl -MO=Deparse -pe 'if($.==1){@L=split;foreach(@L){$_="SING.$_";}$_="@L\n"}'

LINE: while (defined($_ = readline ARGV)) {
    if ($. == 1) {
        @L = split(' ', $_, 0);
        foreach $_ (@L) {
            $_ = "SING.$_";
        }
        $_ = "@L\n";
    }
}
continue {
    die "-p destination: $!\n" unless print $_;
}

Upvotes: 2

reinierpost
reinierpost

Reputation: 8591

The last line combines the modified words into a full line and assigns it to $_, which is what will be printed after processing each line when -p is used. (You might have inferred this from the perlrun manual section on -p.)

Upvotes: 0

Related Questions