"Greg London" <[email protected]> writes:
> (1) given a string containing the name of a scalar,
> how would I tell if that variable already exists in the symbol table?
>
> i.e. given "MyPackage::Varname", how would I tell if
> $MyPackage::Varname was already declared?
> and if it is an array reference?
>
There's a hash defined with the same name (with two colons appended) as
each package in your program . Each key's value is a typeglob. You can
check if a typeglob has a scalar slot filled by using $ on the typeglob
variable's name. I thought you would also be able to look at
*typeglob{SCALAR} but according to perlref this is not so:
*foo{THING} returns undef if that particular THING hasn't been used
yet, except in the case of scalars. *foo{SCALAR} returns a reference
to an anonymous scalar if $foo hasn't been used yet. This might
change in a future release.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#!/usr/pkg/bin/perl
use v5.10;
package MyPackage;
$VarName = '';
package main;
for (qw/VarName WrongVarName/) {
local *st_entry = $MyPackage::{$_};
say "\$MyPackage::$_ ",
(defined($st_entry) ? 'already' : 'not'), ' defined';
}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
$MyPackage::VarName already defined
$MyPackage::WrongVarName not defined
====================================================================
If you have "MyPackage" in a variable as opposed to hard coded in your
program then use a symbolic reference to get to the hash.
When a variable holds an array reference calling ref on it returns
"ARRAY".
Look in perlmod and perlref or Programming Perl for the full explanation.
>
> (2) given a reference to an array, would it be possible to
> convert that reference back into a package name?
>
> i.e. how would I get this code:
>
> package MyOtherPackage;
> our $FancyArrayRef= [ 1,2,3 ];
>
> my $arrref=$FancyArrayRef;
>
> my $name = magicsubroutinehere($arrref);
>
> to end up with $name equal to "MyOtherPackage::FancyArrayRef"?
I don't know. I'd think it's impossible directly. I mean, in this
example you're in the same package, so you have the package name in
__PACKAGE__, but you mean in another context, I presume. What would
$arrref, as a lexical, supposing you handed it out to some other
context, be referencing that could have this information? If I
understand symbol tables and lexicals correctly (hmmm), it would only
point to the array memory object itself, not any of the data in the
symbol table entries. You wouldn't think there'd be any identifying
information down at that level. If it did and you made an alias to the
same array in the symbol table of another package then how would
things jibe?
- Mike
_______________________________________________
Boston-pm mailing list
[email protected]
http://mail.pm.org/mailman/listinfo/boston-pm