in reply to Variable Package Names?
Warning: This is almost definitely not the best way to approach your problem, and if you use it in production code you're more courageous than I -- but it's a tool and I know how to do it. Sufficiently warned:
You could also create $text to eval that contains your package statement and use vars statements or my statements as you see fit.#!/usr/bin/perl -w use strict; BEGIN { my @packages = qw(test test2); my @vars = qw(first second); populate(); sub populate { my $text = ''; foreach my $package (@packages) { foreach my $var (@vars) { $text = '$' . $package . '::' . $var . ' = 1;' . "\n"; print $text; eval $text; } } } } print "test:\t$test::first\t$test::second\n"; print "test2:\t$test2::first\t$test2::second\n";
There's another way, using symbolic references. That's also generally considered a bad idea, because it's easy to cause flaming death with a typo:
#!/usr/bin/perl -w use strict; my @vars = qw(one two three); package main; my ($one, $two, $three) = (1 .. 3); { no strict 'refs'; foreach my $var (@vars) { *{"test::$var"} = $var; } } package test; print "One: $one\tTwo: $two\tThree: $three\n";
|
|---|