脚本中的Perl格式问题



考虑:

#!/usr/bin/perl -w
use strict;
for (my $i=0; $i<=500; $i++)
{
    print "Processing configuration $i...n";
    system("g_dist -s pull.tpr -f conf${i}.gro -n index.ndx -o dist${i}.xvg < groups.txt &>/dev/null");
}

我有一个系统命令,它需要进行格式化,所以基本上这个命令将输入文件提供给Gromacs。我的文件不像conf1.gro、conf2.gro等。它们像0001conf1.gros、0002conf2.gros等。所以我想编辑这个命令,比如:

我试着使用"%04d",因为所有的数字都是四位数,但我不知道如何正确使用零。。。

范围运算符是"magic",可以用来增加字符串,如下所示:

for my $num ( '0001' .. '0010' ) {
    my $conf = "conf$num.gro";
    my $dist = "dist$num.xvg";
    ....
}

有点小技巧,但它做到了:

插入以下行作为循环中的第一行:

while (length($i) < 4) { $i = '0'.$i; }

更好的方式是http://perldoc.perl.org/functions/sprintf.html:

$cmd = sprintf('g_dist -s pull.tpr -f conf%1$04d.gro -n index.ndx -o dist%1$04d.xvg < groups.txt &>/dev/null', $i);

最新更新