http://qs321.pair.com?node_id=131537


in reply to getting at the text of an icon

Short answer: you can't do that; you shouldn't be doing that.

Long answer: you can do it, sometimes; but it's not really a good idea.

For variables in the symbol table, you can find this information, by recursing through the symbol table, with something like this (this example only works on scalars, extending it should be relatively simple, see also perlref):

# This code is not tested. Sorry. sub _find_var_loop { my($hash,$prefix,$var) = @_; my @results; # go through each entry in our symbol table hash... while (my($name,$glob) = each %$hash ) { if ($var eq \${ $glob }) { push @results, $perfix.$var; # add $var to our list } # is it another symbol table hash? # (ignore main:: to not infinite loop) if ($name =~ /::\z/ and $name ne 'main::') { # recurse... push @results, _find_var_loop(\%{ $glob }, $prefix.$name, $var); } } return @results; } sub find_var { # usage: my @names = find_var($var); return _find_var_loop(\%main::, "", \$_[0]) }

This function will find all variables with a certain values in the symbol table, by comparing the "SCALAR(0xDEADBEEF)"-like strings you get when you stringify references. (See also perlref). Note that I say all; there can be multiple copies of a variable in the symbol table when Exporter or the *glob = \$variable or *glob1 = *glob2 syntaxes are used. (This function returns the variable names from the prespective of the main package, since that's where it starts searching from, and I didn't want to have all the results have :: or main:: on the front.)

However, this all won't work for my'd variables, which are generally preferred in perl code. You could probably do my'd variables with some C code, but I wouldn't count on it not breaking in future versions of perl. (There is nothing in the public API to do that.)

Using variables as variable names is, in general, a very bad idea. See this set of articles. So, please, don't do that. You can, with a few rare exceptions, always use (possibly nested) data structures instead of variables as variable names.

update: I realize (impossiblerobot's very closely spaced post reminded me) I didn't emphasize enough that this is going to inefficient. Searching through the symbol table is that way, and that's another reason why it's best left avoided.

Replies are listed 'Best First'.
Re: Re: getting at the text of an icon
by giulienk (Curate) on Dec 13, 2001 at 13:47 UTC
    I agree this is really something not to do in real world programming, but I found it pretty interesting to write some JAPH/Obfu/Poetry. For example:
    package Love; $asami = 'Love'; print "I $asami " . (keys%Love::)[0];
    Anyway moo stated this is not about solving a programming problem so i suppose he is not going to use it in "real" programs.

    gkinueliileunikg