简体   繁体   English

如何使用动态文件句柄动态打开多个文件

[英]How to open the multiple files dynamically using a dynamic file handle

I'm trying to opening multiple files using the a dynamic file handle but it doesn't work. 我正在尝试使用动态文件句柄打开多个文件,但是它不起作用。

for my $i ( 1 .. $#genome_list ) {
    my $fh = "RESULT$i";
    open my $fh, "<", "filename$i"; # here is the problem
}

Then how to access the data of the given handler. 然后如何访问给定处理程序的数据。

When I run the program it shows this error 当我运行程序时,它显示此错误

Can't use string ("RESULT1") as a symbol ref while "strict refs" 

How can I fix it? 我该如何解决?

You're trying to do something that's a little bit nasty , and rather than tell you how to do that, I'm going to suggest an alternative. 您正在尝试做一些令人讨厌的事情 ,而不是告诉您如何做,我将建议一种替代方法。

If you need multiple filehandles open at once, then what you need is a hash : 如果需要一次打开多个文件句柄,则需要一个哈希值

my %file_handle_for;
for my $i ( 1..$#genome_list ) { 
    open ( $file_handle_for{$i}, '<', "filename$i" ) or die $!;
}

Then you can just access the file as: 然后,您可以按以下方式访问文件:

print {$file_handle_for{$i}} "Some text\n"; 

Or: 要么:

while ( <{$file_handle_for{$i}}> ) {
    print;
 }

etc. 等等

That's assuming of course, you need to open all your files concurrently, which you may well not need to. 当然,这是假设,您需要同时打开所有文件,而您可能并不需要打开这些文件。

The above is the general solution to wanting to use variables as variable names. 上面是要使用变量作为变量名称的一般解决方案。

Looking at it in your case though - you're opening files in numeric order with no gaps, and that means an array is better suited. 不过,以您的情况来看-您将以数字顺序打开文件而没有任何间隙,这意味着数组更适合。

my @filehandle_for; 
#note though - arrays start at zero normally, so you might be missing one here!
foreach my $number ( 1..$#genome_list ) { 
  open ( $filehandle_for[$number], '<', "filename$number" ) or die $!;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM