如何使用变量值作为Perl中的名称创建新文件?

4 perl

例如:

$variable = "10000";
for($i=0; $i<3;$i++)
{
   $variable++;
   $file = $variable."."."txt";
   open output,'>$file' or die "Can't open the output file!"; 
}
Run Code Online (Sandbox Code Playgroud)

这不起作用.请建议一种新的方式.

dao*_*oad 17

这里的每个人都说得对,你在电话中使用单引号open.单引号不会将变量插入到带引号的字符串中.双引号呢.

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?
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.但是,其他人忽略了给你一些重要的建议open.

这个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";
Run Code Online (Sandbox Code Playgroud)

关于词法文件句柄有许多好处,但一个优秀的属性是当它们的引用计数降为0并且它们被销毁时它们会自动关闭.没有必要明确地关闭它们.

另外值得注意的是,大多数Perl社区都认为始终使用strictwarnings 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.
}
Run Code Online (Sandbox Code Playgroud)

我也简化了你的代码.我使用范围运算符生成文件名的基数.由于我们使用的是数字而不是字符串,因此我能够使用_千位分隔符来提高可读性,而不会影响最终结果.最后,我使用了一个惯用的perl for循环而不是C风格.

我希望你觉得这有帮助.


gho*_*g74 5

使用双引号:"> $ file".单引号不会插入您的变量.

$variable = "10000";
for($i=0; $i<3;$i++)
{
   $variable++;
   $file = $variable."."."txt";
   print "file: $file\n";
   open $output,">$file" or die "Can't open the output file!";
   close($output);
}
Run Code Online (Sandbox Code Playgroud)