SPUG: Introspective parameters... Can a parameter know it's argument's name from the caller's perspective?
Michael R. Wolf
MichaelRWolf at att.net
Fri Jun 27 17:22:37 PDT 2008
A colleague just asked a question that's related to a question I've had for
years, so here goes my question.
Is there some way that a parameter can know the name of the argument from
the perspective of the caller?
I'd like to do something like this:
($first_name, $last_name, $favorite_language) = qw(Michael Wolf Perl);
foreach $variable first_name, $last_name, $favorite_language) {
debug_blather($variable);
}
And get output like this...
$first_name (in namespace 'main::') has a value of
'Michael'
$last_name (in namespace 'main::') has a value of
'Wolf'
$favorite_language (in namespace 'main::') has a value of 'Perl'
I guess I'm looking for the ability to do introspection on elements of @_.
It might look something like this (in a pseudo-Perl syntax).
sub debug_blather {
foreach my $i (0 .. $#_) { # Ewww, that's ugly!!!
my $vn = $_[$i].variable_name();
my $ns = $_[$i].namespace();
my $val = $_[$i].value();
my $fmt = '...';
printf $fmt, $vn, $ns, $val;
}
Name and value are all I really care about, but other attributes might be
nice (namespace, reference count, etc.).
The big point is that I'd like to pass *one* thing, not two. I can figure
out how to pass a variable (as a symbol) *and* its name (as a string), but
that's double (i.e. redundant (i.e. annoying and fragile)) work! It's not a
DRY (Don't Repeat Yourself) way to work.
And I don't want to resort to hash builders that rely on symbolic variables
because I don't want to deal with strings when I'm really dealing with
identifiers. Symbol table hashes scare me a bit because they break when my
code crashes. They're hard to debug. And I don't know how to do lexicals.
But mostly I want to avoid it because it feels like symbolic references are
a hack (even though I know I could parameterize that hack with __PACKAGE__
and a slew of strings).
Ideas?
P.S. Is this something that's coming in Perl6? If so, every day after
Perl6 will be Christmas!!! :-)
--
Michael R. Wolf
All mammals learn by playing!
MichaelRWolf at att.net
More information about the spug-list
mailing list