如何使用变量值作为Perl中的名称创建新文件?
例如:
$variable = "10000"; for($i=0; $i<3;$i++) { $variable++; $file = $variable."."."txt"; open output,'>$file' or die "Can't open the output file!"; } 这不起作用.请建议一种新的方式. 解决方法
这里的每个人都说得对,你在打电话中使用单引号.
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? 到现在为止还挺好.但是,其他人却没有给你一些关于开放的重要建议. 多年来 经验表明这是一个坏主意.在一个参数中组合模式和文件名会产生安全问题.使用全局变量,正在使用全局变量. 从Perl 5.6.0开始,您可以使用更加安全的3参数形式的open,并且可以将文件句柄存储在词法范围的标量中. open my $fh,'>',$file or die "Can't open $file - $!n"; print $fh "Goes into the filen"; 关于词法文件句柄有许多好处,但一个优秀的属性是当它们的引用计数降为0并且它们被销毁时它们会自动关闭.没有必要明确地关闭它们. 值得注意的是,大多数Perl社区都认为始终使用strict和warnings pragma是一个好主意.使用它们有助于在开发过程的早期捕获许多错误,并且可以节省大量时间. use strict; use warnings; for my $base ( 10_001..10_003 ) { my $file = "$base.txt"; print "file: $filen"; open my $fh,$file or die "Can't open the output file: $!"; # Do stuff with handle. } 我也简化了你的代码.我使用范围运算符生成文件名的基数.由于我们使用的是数字而不是字符串,因此我可以使用_作为千位分隔符来提高可读性,而不会影响最终结果.最后,我使用了一个惯用的perl for循环而不是你的C风格. 我希望你觉得这有帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |