如何以编程方式生成多个 Perl 文件句柄?

发布于 2024-08-17 13:05:21 字数 165 浏览 2 评论 0原文

Perl 有没有办法以编程方式生成文件句柄?

我想同时打开十个文件并使用由(常量名称+数字)组成的文件句柄写入它们。例如:

 print const_name4  "data.."; #Then print the datat to file #4

Is there any way in Perl to generate file handles programmatically?

I want to open ten files simultaneously and write to them by using file handle which consists of (CONST NAME + NUMBER). For example:

 print const_name4  "data.."; #Then print the datat to file #4

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

颜漓半夏 2024-08-24 13:05:21

您可以将文件句柄直接粘贴到未初始化的数组槽中。

my @handles;
for my $number (0 .. 9) {
    open $handles[$number], '>', "data$number";
}

不要忘记打印到数组中的句柄的语法略有不同:

print $handles[3] $data;    # syntax error
print {$handles[3]} $data;  # you need braces like this

You can stick filehandles straight into an uninitialised array slot.

my @handles;
for my $number (0 .. 9) {
    open $handles[$number], '>', "data$number";
}

Don't forget that the syntax for printing to a handle in an array is slightly different:

print $handles[3] $data;    # syntax error
print {$handles[3]} $data;  # you need braces like this
想你只要分分秒秒 2024-08-24 13:05:21

带有一点 IO::File< /a> 和 map 你也可以这样做:

use IO::File;

my @files = map { IO::File->new( "file$_", 'w' ) } 0..9;

$files[2]->print( "writing to third file (file2)\n" );

With a bit of IO::File and map you can also do this:

use IO::File;

my @files = map { IO::File->new( "file$_", 'w' ) } 0..9;

$files[2]->print( "writing to third file (file2)\n" );
染年凉城似染瑾 2024-08-24 13:05:21

如今,您可以将文件句柄分配给标量(而不是使用表达式(如您的示例所示)),因此您只需创建一个数组并用它们填充它即可。

my @list_of_file_handles;
foreach my $filename (1..10) {
    open my $fh, '>', '/path/to/' . $filename;
    push $list_of_file_handles, $fh;
}

当然,您可以使用 变量 代替,但它们是一种令人讨厌的方法,我'从来没有见过使用数组或哈希不是更好的选择的时候。

These days you can assign file handles to scalars (rather than using expressions (as your example does)), so you can just create an array and fill it with those.

my @list_of_file_handles;
foreach my $filename (1..10) {
    open my $fh, '>', '/path/to/' . $filename;
    push $list_of_file_handles, $fh;
}

You can, of course, use variable variables instead, but they are a nasty approach and I've never seen a time when using an array or hash wasn't a better bet.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文