脚本中的 Perl 格式化问题
Perl formatting issues in a script
考虑:
#!/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”,因为所有数字都是四位数字,但我不知道如何在这里正确使用从零开始的...
有点老套,但它确实有效:
将以下行作为第一行插入循环中:
while (length($i) < 4) { $i = '0'.$i; }
更好的方法是合并 http://perldoc.perl.org/functions/sprintf.html:
$cmd = sprintf('g_dist -s pull.tpr -f conf%1d.gro -n index.ndx -o dist%1d.xvg < groups.txt &>/dev/null', $i);
range operator 是 "magic",可用于递增字符串,如下所示:
for my $num ( '0001' .. '0010' ) {
my $conf = "conf$num.gro";
my $dist = "dist$num.xvg";
....
}
考虑:
#!/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”,因为所有数字都是四位数字,但我不知道如何在这里正确使用从零开始的...
有点老套,但它确实有效:
将以下行作为第一行插入循环中:
while (length($i) < 4) { $i = '0'.$i; }
更好的方法是合并 http://perldoc.perl.org/functions/sprintf.html:
$cmd = sprintf('g_dist -s pull.tpr -f conf%1d.gro -n index.ndx -o dist%1d.xvg < groups.txt &>/dev/null', $i);
range operator 是 "magic",可用于递增字符串,如下所示:
for my $num ( '0001' .. '0010' ) {
my $conf = "conf$num.gro";
my $dist = "dist$num.xvg";
....
}