F/lix has asked for the wisdom of the Perl Monks concerning the following question:

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

Replies are listed 'Best First'.
Re: Updating file name
by ikegami (Patriarch) on Aug 04, 2006 at 19:05 UTC

    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
by imp (Priest) on Aug 04, 2006 at 19:08 UTC
    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
by friedo (Prior) on Aug 04, 2006 at 19:05 UTC
    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
by F/lix (Initiate) on Aug 04, 2006 at 19:18 UTC
    Many thanks. Sometimes it's just too simple!
A reply falls below the community's threshold of quality. You may see it by logging in.