in reply to creating variables in a loop

First, I must suggest using an array. That would be the most simple. Then all you would need would be:

my $cnt = 0; my @q; for ( 1 .. 40 ) { $cnt++; $q[ $cnt ] = param( "q$cnt" ); }

If you are DYING to use variables named $q11, etc., it is possible. However, I recently maintained a webpage that went with this method, and I was pretty close to strangling the original writing and yelling at him to learn how to use arrays (but I refrained). Anyway, enough with my story, to do that, you would need to do something like this (I think, this is untested, and I don't know what the scope will be).

my $cnt = 0; for ( 1 .. 40 ) { $cnt++; eval( "my \$q$cnt = param( \"q\$cnt\" );" ); }

I do think you would be better off with an array in the end. I can not think of any good reason that you would necessarily need to have 40 seperately named variables instead of one array.

-Bryan

Update:
Removed 'my' from first example, thanks to merlyn pointing out my error.

Replies are listed 'Best First'.
Re^2: creating variables in a loop
by Fletch (Bishop) on May 19, 2005 at 00:14 UTC

    merlyn's points aside, it's still broken because you still have a my inside your eval'd string and the lexical will disappear with the BLOCK of the enclosing for.

    $ perl -le 'use strict; for( 1..2 ) { eval qq{my \$q$_ = $_}; }; print + $q1' Global symbol "$q1" requires explicit package name at -e line 1.
Re^2: creating variables in a loop
by merlyn (Sage) on May 18, 2005 at 22:33 UTC

      Yes, of course I remember what you said. In this case, in my example, it's not a security flaw. I can tell you exactly what $cnt is going to be every time, and everything else is escaped.

      I presented it as an answer to his question. I thought your bias on eval was because of security, not absolutely against any use of eval, but maybe I was mistaken?

      -Bryan

        never never never use eval $string. Clearer now?

        When you use eval $string, you fire up a compiler. And there's no point, because every part of this is known by the time you are executing this code.

        You're also using eval to get around "use strict", so even if it's not objectionable on a security basis, it's objectionable on a never never never use "variable variables" basis.

        -- Randal L. Schwartz, Perl hacker
        Be sure to read my standard disclaimer if this is a reply.