Search code examples
perlpattern-matchingdigits

Manipulating digits


This is a program which grabs lines which contains the $position AND $amino value in the first two columns.

Code:

#!/usr/bin/perl

my $id = $ARGV[0];
my $position = $ARGV[1]; # POSITION OF THE RESIDUE
my $amino= $ARGV[2]; #THREE LETTER AMINO ACID CODE IN CAPITALS
my @grabbed;

open (FILE, $id.$amino.$position.".hb2");

#CREATES AN ARRAY WITH ONLY THE VALUES FROM THE HB2 FILE. REMOVES THE HEADER OF THE FILE.

while (<FILE>) {
    if (/^-/) {
            push @grabbed, $_;
            while (<FILE>) {
            last if /^$/;
            push @grabbed, $_;
            }

    }
}
close (FILE);


for ( @grabbed ) {
my @f = split;
if (( $f[2] == "-"."00".$position."-".$amino ) or ($f[0] == "-"."00".$position."-".$amino)) {
    push @line, $id.$amino.$position, " ",$_;
}
}
print @line;

Partial input data :

-0007-ARG NH2 -0009-GLN OE1 3.24 SS   2  6.00 143.3  2.38 105.9  95.8     1 #CASE 1
-0008-GLU N   -0008-GLU OE1 2.62 MS   0 -1.00 120.8  1.96 102.3 103.4     2
-0011-ILE N   -0117-ARG O   2.87 MM 106  4.90 144.0  2.00 127.5 139.0     3 
-0117-ARG N   -0011-ILE O   2.75 MM 106  4.90 160.4  1.79 153.2 148.6     4 #CASE 2
-0016-SER N   -0012-THR O   2.89 MM   4  6.00 156.2  1.95 149.8 154.8     5 #CASE 3
-0017-ALA N   -0013-LEU O   3.10 MM   4  6.24 152.8  2.17 143.4 149.7     6
-0018-GLU N   -0014-ARG O   3.04 MM   4  6.24 154.1  2.11 147.2 154.2     7
-0019-ILE N   -0015-GLY O   2.90 MM   4  6.16 155.8  1.96 150.7 156.2     8
-0016-SER OG  -0188-THR OG1 2.72 SS 172  5.92 172.0  1.73  98.9  99.6     9
-0188-THR OG1 -0016-SER OG  2.72 SS 172  5.92 163.7  1.75 116.4 115.1    10

Question :

In order to generalize the program I made the match as :

( $f[2] == "-"."00".$position."-".$amino ) or ($f[0] == "-"."00".$position."-".$amino)

The format is always four digits after "-" before $amino (-0188-THR). I suddenly realized that my code wouldnt work if the $position input is "one digit(like CASE 1)" or "three digit (like CASE 2, column 1)". Since I hard coded it as format as "-" followed by two zeros and THEN position, it has to always be two digit input to work.

I am stumped to generalize this code so that I could put in 1/2/3 digits. The remaining digits would always be replaced by zeros.


Solution

  • First, == operator in perl used only for comparing arithmetic expressions To compare strings you should use eq operator
    Second, to format strings from digits you can use sprintf function.

    if ($f[2] eq "-".sprintf("%04d", $position)."-".$amino ...