例如:
$variable = "10000"; for($i=0; $i<3;$i++) { $variable++; $file = $variable."."."txt"; open output,'>$file' or die "Can't open the output file!"; }
这不起作用.请建议一种新的方式.
解决方法@H_502_17@
这里的每个人都说得对,你在打电话中使用单引号.
Single quotes do not interpolate variables into the quoted string. Double quotes do.
my $foo = 'cat';
print 'Why does the dog chase the $foo?'; # prints: Why does the dog chase the $foo?
print "Why does the dog chase the $foo?"; # prints: Why does the dog chase the cat?
到现在为止还挺好.但是,其他人却没有给你一些关于开放的重要建议.
多年来open
功能一直在发展,Perl使用文件句柄的方式也是如此.在过去,总是使用模式调用open,并在第二个参数中组合文件名.第一个参数始终是全局文件句柄.
经验表明这是一个坏主意.在一个参数中组合模式和文件名会产生安全问题.使用全局变量,正在使用全局变量.
从Perl 5.6.0开始,您可以使用更加安全的3参数形式的open,并且可以将文件句柄存储在词法范围的标量中.
open my $fh,'>',$file or die "Can't open $file - $!\n";
print $fh "Goes into the file\n";
关于词法文件句柄有许多好处,但一个优秀的属性是当它们的引用计数降为0并且它们被销毁时它们会自动关闭.没有必要明确地关闭它们.
值得注意的是,大多数Perl社区都认为始终使用strict和warnings pragma是一个好主意.使用它们有助于在开发过程的早期捕获许多错误,并且可以节省大量时间.
use strict;
use warnings;
for my $base ( 10_001..10_003 ) {
my $file = "$base.txt";
print "file: $file\n";
open my $fh,$file or die "Can't open the output file: $!";
# Do stuff with handle.
}
我也简化了你的代码.我使用范围运算符生成文件名的基数.由于我们使用的是数字而不是字符串,因此我可以使用_作为千位分隔符来提高可读性,而不会影响最终结果.最后,我使用了一个惯用的perl for循环而不是你的C风格.
我希望你觉得这有帮助.
my $foo = 'cat'; print 'Why does the dog chase the $foo?'; # prints: Why does the dog chase the $foo? print "Why does the dog chase the $foo?"; # prints: Why does the dog chase the cat?
到现在为止还挺好.但是,其他人却没有给你一些关于开放的重要建议.
多年来open
功能一直在发展,Perl使用文件句柄的方式也是如此.在过去,总是使用模式调用open,并在第二个参数中组合文件名.第一个参数始终是全局文件句柄.
经验表明这是一个坏主意.在一个参数中组合模式和文件名会产生安全问题.使用全局变量,正在使用全局变量.
从Perl 5.6.0开始,您可以使用更加安全的3参数形式的open,并且可以将文件句柄存储在词法范围的标量中.
open my $fh,'>',$file or die "Can't open $file - $!\n"; print $fh "Goes into the file\n";
关于词法文件句柄有许多好处,但一个优秀的属性是当它们的引用计数降为0并且它们被销毁时它们会自动关闭.没有必要明确地关闭它们.
值得注意的是,大多数Perl社区都认为始终使用strict和warnings pragma是一个好主意.使用它们有助于在开发过程的早期捕获许多错误,并且可以节省大量时间.
use strict; use warnings; for my $base ( 10_001..10_003 ) { my $file = "$base.txt"; print "file: $file\n"; open my $fh,$file or die "Can't open the output file: $!"; # Do stuff with handle. }
我也简化了你的代码.我使用范围运算符生成文件名的基数.由于我们使用的是数字而不是字符串,因此我可以使用_作为千位分隔符来提高可读性,而不会影响最终结果.最后,我使用了一个惯用的perl for循环而不是你的C风格.
我希望你觉得这有帮助.