Creating a file to print to

R

Robert

Hello,

I am trying to create different files to print data to.
The problem I am having is with the name of the file.

I have created a loop to create the files, which works fine,
however later in the program I need to write similar data to the file.

This is what I am doing but it does not work:

while ($group <=12){

print MY.$group.OUTFILE $header_top;
print MY.$group.OUTFILE "$group";
print MY.$group.OUTFILE "$header_bottom;
$group++;

}

How can I get the "reference to the file" to change name?

At the moment I am forced to type:

$group = "12";
print MY12OUTFILE $header_top;
print MY12OUTFILE "$group";
print MY12OUTFILE $header_bottom;

$group = "11";
print MY11OUTFILE $header_top;
..............
..............

Any suggestions?
 
M

Mumia W.

Hello,

I am trying to create different files to print data to.
The problem I am having is with the name of the file.

I have created a loop to create the files, which works fine,
however later in the program I need to write similar data to the file.

This is what I am doing but it does not work:

while ($group <=12){

print MY.$group.OUTFILE $header_top;
print MY.$group.OUTFILE "$group";
print MY.$group.OUTFILE "$header_bottom;
$group++;

}

How can I get the "reference to the file" to change name?

At the moment I am forced to type:

$group = "12";
print MY12OUTFILE $header_top;
print MY12OUTFILE "$group";
print MY12OUTFILE $header_bottom;

$group = "11";
print MY11OUTFILE $header_top;
..............
..............

Any suggestions?

Yes,

use IO::File;

my %groups = (
11 => IO::File->new(...) || die(...),
12 => IO::File->new(...) || die(...),
);

my $group = 1;

while ($group <= 12) {
next unless $groups{$group};
print { $groups{$group} } $header_top;
print { $groups{$group} } $group;
print { $groups{$group} } $header_bottom;
$group++;
}

# Close the IO::File objects in %groups.

__UNTESTED_CODE__

Read the doc for "print" again: "perldoc -f print"
 
P

Peter J. Holzer

use IO::File;

Not necessary. open works just fine since at least 5.8.

my %groups = (
11 => IO::File->new(...) || die(...),
12 => IO::File->new(...) || die(...),
);

my $group = 1;

while ($group <= 12) {

Why are you using a hash if it is indexed by small, consecutive
integers?

hp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top