How can I generate multiple Perl program files programmatically?

Is there any way in Perl for programmatically processing files?

I want to open ten files at once and write them using a file descriptor that consists of (CONST NAME + NUMBER). For instance:

 print const_name4  "data.."; #Then print the datat to file #4
+3
source share
3 answers

You can insert file descriptors directly into an uninitialized array slot.

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

Do not forget that the syntax for printing in the descriptor in the array is slightly different:

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

With a small amount IO::Fileand 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" );
+5
source

( ( )), .

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 this is an unpleasant approach, and I never saw the time when using an array or hash was not the best bet.

+3
source

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


All Articles