[Techtalk] Perl Frustration
Kai MacTane
kmactane at GothPunk.com
Thu Oct 30 19:09:57 EST 2003
I'm having a hard time trying something in Perl, and neither the Camel Book
nor Google has been no help.
I want to declare a set of variables inside a loop, and have them be
accessible to the rest of the program. It's not known until run-time just
how many of these variables there are, or what their names will be. (They
may be acquired from user input, or from a configuration file.)
I can do this the "insecure newbie" way, by not using strict checking or
predeclaring any variables. But that's so naff it hurts.
I'm now trying to convert some old scripts of mine to "use strict" (and
taint checking, and warnings). Now I need to declare all variables with
"my" -- but that makes them local to their innermost enclosing block, so
they're not visible outside the loop.
I have situations like this in a variety of scripts, so I'll just post some
code that tries to boil the problem down to a very generalized case:
print "Enter names of some variables (blank to finish)...\n";
my $thisline;
chomp($thisline = <STDIN>);
while ($thisline =~/\w/) {
$foovar = $thisline.'_foo';
$$foovar = $thisline;
chomp($thisline = <STDIN>);
}
# Now print out the main symbol table. (Code adapted from
# Camel Book, p. 281.)
foreach $symname (sort keys %main::) {
local *sym = $main::{$symname};
next if ($symname !~ /^\w/);
print "\$$symname is defined\n" if defined $sym;
# print "\@$symname is defined\n" if defined @sym;
# print "\%$symname is defined\n" if defined %sym;
}
If I run this code, and enter "foo", "bar", and "wombat" for the user
input, the output shows me that variables $foo_foo, $bar_foo and
$wombat_foo have been created. But if I turn on "use strict" at the
beginning, and try to do:
my ($$foovar) = $thisline;
or even
my (${$foovar}) = $thisline;
I get: Can't declare scalar dereference in ./testing my at line 11 near ") ="
I know there must be a way to do this, but how? Thanks in advance.
--Kai MacTane
----------------------------------------------------------------------
"Then, when they spill the demon seed
Turn and face into the wind.
All along you still believed...
Believed you were immune."
--Thomas Dolby,
"The Flat Earth"
More information about the Techtalk
mailing list