Home > Mobile >  Perl one-liner that combines two if statements into one
Perl one-liner that combines two if statements into one

Time:12-09

I have written a perl code in a script format. Here is the script:

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

    while(<>){
        chomp;
        my @s = split /\t/,$_;
        if($_ =~ /NM:i:(\d ) and $1 >= 7/){
            print $_,"\n";
        }
    }

I want to write this perl script.pl code in perl one liner fashion. Itried something like this, but it is failing to do what I expect it to do:

perl -ne '@s = split; if $_ =~ /NM:i:(\d )/{ print if $1 >=7}'

How to fix this? Thanks

CodePudding user response:

perl -ne'print if /NM:i:(\d )/ && $1 >= 7'

You have a needless split on tab in there. But let's say you actually needed it. If so, you could use

perl -F'\t' -lane'print if $F[0] =~ /NM:i:(\d )/ && $1 >= 7'

This only matches against the first field.


does that mean in my script.pl, I can avoid 2 if statements?

Yes.

Aside from scoping differences, the following are equivalent:

if (f()) {
   if (g()) {
      h();
   }
}

if (f() && g()) {
   h();
}

h() if f() && g();

f() && g()
   and h();

CodePudding user response:

I tend to think about these problems as the lines to skip rather than the lines to output. But, the combination of the conditions is the same as what ikegami has already shown:

perl -pe 'next unless(/NM:i:(\d )/ && $1 >= 7)' ...
  •  Tags:  
  • perl
  • Related