创建文件 aa..zz 并使用范围运算符将 AA..ZZ 写入文件
我对 Perl 很陌生,有一个问题。我正在尝试在目录中创建文件并写入这些文件。这是我到目前为止所拥有的,它创建了目录,但没有在其中写入任何内容。我不知道如何写入文件,我已经考虑过创建一个三通或多维数组,但这不起作用。
#!/usr/bin/perl
use strict;
use warnings;
my @alpha = ("aa".."bb");
for my $combo(@alpha)
{
open(DFILE,"+>$combo") || die "die open failed";
while (<DFILE>)
{
print $_;
}
close(DFILE);
}
I am very new to perl and have a question. I am trying to create files in a directory and write to those files. Here is what I have so far, it creates the directories but doesn't write anything in them. I can't figure out how to write to the files, I've looked at creating a tee or multidimensional array but that didn't work.
#!/usr/bin/perl
use strict;
use warnings;
my @alpha = ("aa".."bb");
for my $combo(@alpha)
{
open(DFILE,"+>$combo") || die "die open failed";
while (<DFILE>)
{
print $_;
}
close(DFILE);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
下面创建 28 个文件并将文件名的大写写入到文件中。例如,它创建一个名为
aa
的文件,其中包含一行:AA
。请参阅File::Slurp。
The following creates 28 files and writes the upper case of filename to the file. For example, it creates a file named
aa
containing one line:AA
.See File::Slurp.
简而言之,要向使用 DFILE 句柄打开的文件写入内容,您应该使用
但我对您的目标有点困惑,尤其是您到底要写入这些文件的内容。你能澄清一下吗?
In short, to write something to a file opened with DFILE handle, you should use
But I'm confused about your goals a bit, especially about what exactly you're going to write to these files. Could you clarify it?
您打开文件用于写入(
>
),并增强文件用于读取(+
)。打开文件后,您可以从其文件句柄中读取内容并将读取的内容打印到默认文件句柄 (STDOUT
)。完成后,关闭文件。如果该文件尚不存在,您将创建该文件,不会有任何内容可供读取(也没有任何内容可打印),并且您将关闭仍然为空的文件。
我不知道你想做什么。如果您尝试向文件添加行,则可以打开它进行追加 (
>>
)。当您想要打印到该文件句柄时,您必须告诉print
您要使用哪个文件句柄:这会生成具有如下输出的文件:
如果您尝试打印到文件并打印到标准同时输出(因为您提到了 tee),您可以创建一个多路复用到一个或多个其他文件句柄的文件句柄。 IO::Tee 可以为您做到这一点:
现在每个输出行都转到两个地方:屏幕和文件。
You're opening files for writing (the
>
), and enhancing that for reading (the+
). After you open the file, you read from its filehandle and printing what you read to the default filehandle (STDOUT
). When you're done, you close the file.If the file doesn't already exist, you'll create the file, there won't be anything to read (and nothing to print), and you'll close the still empty files.
I don't know what you are trying to do. If you are trying to add lines to a file, you can open it for append instead (
>>
). When you want to print to that filehandle, you have to tell theprint
which filehandle you'd like to use:This produces files with output like:
If you are trying to print to the file and to standard output at the same time (since you mention a tee), you can create a filehandle that multiplexes to one or more other file handles. The IO::Tee can do that for you:
Now each output lines goes to two places: the screen and the file.