How can I write to Perl files that I stored in an array?

I have a list of file names. I need to create a file for each of these names, write the lines to different files (in a specific order), and then close them.

How can I do this in perl? I foresee something like the following code (which will not work on this form and give syntax errors):

my @names = qw(foo.txt bar.txt baz.txt); my @handles; foreach(@names){ my $handle; open($handle, $_); push @handles, $handle; } # according to input etc.: print $handles[2] "wassup"; print $handles[0] "hello"; print $handles[1] "world"; print $handles[0] "..."; foreach(@handles){ close $_; } 

How can I do it right?

+4
source share
3 answers

Here's how I would do it (untested, but I'm sure this is good):

 use IO::File; # ... my @handles = map { IO::File->new($_, 'w') } @names; $handles[2]->print("wassup"); # ... 

This is OO, it has a cleaner interface, and you don't need to worry about closing it, as it will die when the array goes out of scope.

+2
source

The print file descriptor argument must be a simple word, a simple scalar, or block. So:

 print { $handles[0] } ... 

This is explained in perldoc -f print . The same restriction applies to the indirect syntax object as a whole, as well as to determine when <> is a read operation, not a glob operation.

+13
source

Source: https://habr.com/ru/post/1285942/


All Articles