脚本中的Perl格式化问题

时间:2015-02-07 12:09:18

标签: 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.gro,0002conf2.gro等。所以我想编辑这个命令,如:

我尝试使用“%04d”,因为所有数字都是四位数字,但我不知道如何在这里正确使用零基础...

2 个答案:

答案 0 :(得分:5)

range operator是&#34;魔法&#34;,可以用来增加这样的字符串:

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

答案 1 :(得分:-1)

有点hacky,但它有诀窍:

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

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);