Let's say I have this:
my %data = (id => 'pmak', name => 'Philip Mak', level => 50);
magic_function(\%data);
What could I put for magic_function() such that it'll have this effect,
based on the keys and values of the hash passed to it:
my $id = 'pmak';
my $name = 'Philip Mak';
my $level = 50;
Just to show how unwise this is, here's what it would take to
literally satisfy your request:
sub magic_function {
use Filter::Simple sub {
s/^\s*magic_function\s*\(\s*\\\s*%(\w+).*?;/my \$id = \$$1\{id\};/mg
};
BEGIN { import() }
}
my %data = (id => 'pmak', name => 'Philip Mak', level => 50);
magic_function(\%data);
print "id = $id\n";
Extension to handle the other variables is left as an exercise
for the reader. It also requires that all the keys be
explicitly named. But this is sick; don't do it.
Why would you ask for this in the first place? If you're
going to write code containing $id, for example, why not write
$data{id}, or, if you're going to repeatedly refer to that
and want to save space, write my $id = $data{id} and then go
on to use $id?
More importantly, why would you want to create something that
has unpredictable side effects, so that if one day a new key
gets added to the hash that happens to match a variable you're
already using, your program will fail in some bizarre way?
If the equivalent of %data in the real code is a long
expression you don't want to type repeatedly, then just make
a reference to it:
my $hr = \%blahblahblah...
... $hr->{id} ...
When you see a variable in your program you want to have a
fighting chance of figuring out where it came from.