Updating file name
F/lix
created: 2006-08-04 15:01:31
Hello all, I have to repeat 15 times the same operation writing (different) data into .dat files. The basic name of the file is user-defined and stored in a variable, say $File. What I'd like to do is to add an extension to that file name to have something like : File1.dat, File2.dat and so on. I've tried to put all this in a FOR loop but it obviously doesn't work. Here's part of what I've done:
! for ($j=1;$j<=2;$j++) {
!  $FileName= $File$j.dat;
! }
The problem seems to be in the two $ that appear there. How do you solve the problem? Many thanks, Felix
Re: Updating file name
created: 2006-08-04 15:05:18

Use the string concatenation operator
$FileName= $File . $j . ".dat";
or use interpolation
$FileName= "$File$j.dat";

By the way,
for (my $j=1;$j<=2;$j++)
is not nearly as readable as
for my $j (1..2)

Re: Updating file name
created: 2006-08-04 15:05:41
You can use Perl's concatenation (dot) operator to combine strings:

for(1..2) { 
    my $filename = $file . "$_.dat";
}

Update: s/j/_/;

Re: Updating file name
imp
created: 2006-08-04 15:08:38
You either need to concatenate the values using '.':
  $FileName= $File . $j . '.dat';
Or interpolate them inside double quotes:
  $FileName= "$File$j.dat";
Or you can always use sprintf:
  $FileName= sprintf '%s%d.dat', $File, $j;
Re: Updating file name
created: 2006-08-04 15:18:31
Many thanks. Sometimes it's just too simple!
Re: Updating file name
created: 2006-08-05 05:21:06
Hi [F/lix],

You can get it like this,
#!/bin/perl-w
use strict;
my $File = "File";
for (1..2) {
		my $FileName= "$File"."$_".'.dat';
		print"Filename=> $FileName\n";
}
Thanks and Regards,
madtoperl.

perlmonks.org content © perlmonks.org and F/lix, friedo, ikegami, imp, madtoperl

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03