如何处理 perl 中的格式?

如何处理 perl 中的格式?

我想使用 Perl 脚本将数字写成两位小数。这是我的代码。

#!/usr/bin/perl -w

print "Preparing input files\n";

$incr=0.10;

&prepare_input();

exit(0);

sub prepare_input() {
    
    $dist=3;
    while ($dist <= 23) { 
    print "Processing distral: $dist\n";
    &write_mdin0();
    &write_mdin1();
    &write_mdin2();
    &write_disang();
      $dist += $incr;
    }
}

sub write_mdin0 {
    open MDINFILE,'>', "min_mdin.$dist";
    print MDINFILE <<EOF;
#5000 step minimization for $dist ang
 &cntrl
  imin = 1,
  maxcyc=10000, ncyc = 5000,
  ntpr = 100, ntwr = 1000,
  ntf = 1, ntc = 1, cut = 10.0,
  ntb = 1, ntp = 0,
  nmropt = 1,
 &end
 &wt
  type='END',
 &end
DISANG=disang.$dist

EOF
    close MDINFILE;
}
sub write_mdin1 {
    open MDINFILE,'>', "equi_mdin.$dist";
    print MDINFILE <<EOF;
#10 ns NVT equilibration for $dist ang
 &cntrl
  imin = 0, ntx = 1, irest = 0,
  iwrap = 1,
  ntpr = 5000, ntwr = 50000, ntwx = 0,
  ntf = 2, ntc = 2, cut = 10.0,
  ntb = 2, nstlim = 5000000, dt = 0.002,
  tempi=0.0, temp0 = 300.0, ntt = 3,
  gamma_ln = 5.0,
  ntp = 1, pres0 = 1.0, taup = 5.0,
  nmropt = 1, ioutfm=1,
 &end
 &wt
  type='END',
 &end
DISANG=disang.$dist

EOF
    close MDINFILE;
}
sub write_mdin2 {
    open MDINFILE,'>', "prod_mdin.$dist";
    print MDINFILE <<EOF;
#20 ns NPT production for $dist ang
 &cntrl
  imin = 0, ntx = 5, irest = 1,
  iwrap = 1,
  ntpr = 10000, ntwr = 10000, ntwx = 10000,
  ntf = 2, ntc = 2, cut = 10.0,
  ntb = 2, nstlim = 10000000, dt = 0.002,
  temp0 = 300.0, ntt = 3,
  gamma_ln = 5.0,
  ntp = 1, pres0 = 1.0, taup = 5.0,
  nmropt = 1, ioutfm = 1,
 &end
 &wt
  type='DUMPFREQ', istep1=10,
 &end
 &wt
  type='END',
 &end
DISANG=disang.$dist
DUMPAVE=distance_$dist.dat
EOF
    close MDINFILE;
}
sub write_disang {
 $min   = sprintf "%4.6f", $dist;

    open DISANG,'>', "disang.$dist";
    print DISANG <<EOF;
#Harmonic restraints for $dist ang
 &rst iat=-1,-1,0
   r1=0.000000, r2=$min, r3=$min, r4=99.000000, rk2=5.00000, rk3=5.00000,
  IGR1(1)=1,IGR1(2)=5,IGR1(3)=17,IGR1(4)=19,IGR1(5)=21,IGR1(6)=34,IGR1(7)=36,IGR1(8)=38,IGR1(9)=53,IGR1(10)=55,IGR1(11)=57,IGR1(12)=69,IGR1(13)=71,IGR1(14)=73,IGR1(15)=90,IGR1(16)=92,IGR1(17)=94,IGR1(18)=112,
   IGR2(1)=116,IGR2(2)=120,IGR2(3)=132,IGR2(4)=134,IGR2(5)=136,IGR2(6)=149,IGR2(7)=151,IGR2(8)=153,IGR2(9)=168,IGR2(10)=170,IGR2(11)=172,IGR2(12)=184,IGR2(13)=186,IGR2(14)=188,IGR2(15)=205,IGR2(16)=207,IGR2(17)=209,IGR2(18)=227, 
  nstep1=0, nstep2=0,
 &end
EOF
    close DISANG;
}

这些代码生成这种文件:

min_mdin.8.99999999999998
min_mdin.9.09999999999998

我的目标是生成以下类型的文件:

min_mdin.9.00
min_mdin.9.10

答案1

使用

sprintf "%4.2f"

正如评论中指出的那样

相关内容