wstarrs has asked for the wisdom of the Perl Monks concerning the following question:

For instance I am trying to loop through an array/list of file names and pull only the first three and then trying to assign each of the files to a new variable for later use:
for ($x=0; $x<3; $x++) { @perschecked[$x] = $Persfile$x; }
I know that my syntax is wrong on the $Persfile$x part, how to I express it if I want the file names to to be Persfile1, Persfile2... the number at the end of the variable needs to match the x placeholder? Thanks, bill

Replies are listed 'Best First'.
Re: How do I append an extension onto a variable name?
by Ovid (Cardinal) on May 10, 2001 at 23:40 UTC

    Generally, appending something to another variable uses the dot (.) operator.

    How to do what you want depends upon where you are storing your original filenames. Assuming that you have them in an array named @files and you want to stuff them in an array names @perschecked:

    # alternately, you may want to push them onto @perschecked for my $x ( 0 .. 2 ) { $perschecked[ $x ] = $files[ $x ] . ( $x + 1 ); }

    If you want to append $x in place:

    for my $x ( 0 .. 2 ) { $files[ $x ] .= ( $x + 1 ); }

    Note that the $x + 1 is in there because the array index is one lower than the position of the element.

Re: How do I append an extension onto a variable name?
by srawls (Friar) on May 11, 2001 at 03:57 UTC
    The short answer to your question is to use symbolic references:
    $perschecked[$_] = ${Persfile . $_} for (0 .. 2);
    First of all, notice I changed @perschecked[$x] to $perschecked[$_], I assume this is just a typo, but I brought it up just in case.

    The long answer is not to use symbolic references, because if you use -w, then it will be flagged as an error. The best option is to redisign your data-structure, of course if you can't do this then symbolic references may be needed, and you would have to localize $^W to allow symbolic references.

    The 15 year old, freshman programmer,
    Stephen Rawls

Re: How do I append an extension onto a variable -name-?
by Anonymous Monk on May 11, 2001 at 10:02 UTC
    You're trying to make new variables called $Persfile1, $Persfile2, $Persfile3? You shouldn't do that (its bad practise since we have hashes), but instead use them from the array later or put them in a hash:
    %Persfile = ( 1 => "$perschecked[0]1", 2 => "$perschecked[1]2", 3 => "$perschecked[2]3", );
    Its kind of wordy, but pretty clear and the hash is easy to use later.

    HTH

    J