Operating System - HP-UX
1832859 Members
2713 Online
110048 Solutions
New Discussion

Re: Dynamic file_name problem

 
SOLVED
Go to solution
Vittorio_3
Advisor

Dynamic file_name problem

Hi,I'm looking at perl script that should read control file and write multiple output files making their name dynamic. And I can't make $newfile work with dynamic $count component in its name. Copy step doens't work at all. Is it any way to make it work in Perl.
======================================
$count = 0;
$inp= "input.txt";
open(fileIN, "input.txt");

while () {
open(fileOUT, '>>out1.txt') or die "Can't open output file.\n";
$count = $count + 1 ;
chomp ($_);
print fileOUT $_ . ".ryba.dat\n" ;
$newfile = "ini\_$count\.txt "; #XXX !!!!!!! here

copy($file1, $newfile) or die "File cannot be copied.";
}

===========
tx to all
Dai
7 REPLIES 7
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Dynamic file_name problem

You need to "discover" the sprintf function.

$newfile = sprintf("ini_%d.txt",$count);

The formatting works just line the printf, fprintf, and sprintf C functions so a man sprintf will tell you everything you need to know.
If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: Dynamic file_name problem

Hi:

If this is perl under Unix, your copy command should look like:

system("cp $file1 $newfile") or die "Can't copy!";

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: Dynamic file_name problem

Hi (again):

Well, if you have used the File::Copy module, then I apologize, your 'copy' syntax is correct.

Regards!

...JRF...
Vittorio_3
Advisor

Re: Dynamic file_name problem

Tx to all,
sure I'm using:
use File::Copy

Dai
Vittorio_3
Advisor

Re: Dynamic file_name problem

It works fine now,
Thanks again to everybody.
Just another small question: can I somehow maintain $count like 01,02,etc e.g. 2 digits, as I need that format for my file name. ini_01.txt

Tx
Dai
James R. Ferguson
Acclaimed Contributor

Re: Dynamic file_name problem

Hi:

$newfile = sprintf("ini_%02d.txt",$count);

Note the leading zero with a width of two. See the man pages for 'printf' for more information.

Regards!

...JRF...
A. Clay Stephenson
Acclaimed Contributor

Re: Dynamic file_name problem

If you have been a little less lazy and checked the man page to which I referred you, you could have answered your own question about leading zeroes and learned even more about the power of sprintf.
If it ain't broke, I can fix that.