Moreover, how to know whether an arbitrary package has a specific global# So, how to get $Foo::Str without soft ref?
1. various ways.
a) Any symbol table your current symbol table knows about - is in the current symbol table. So:
use strict; package Foo; use vars qw($str); # $Foo::str created $str = 'foo str'; package main; my $pack = "Foo::"; my $var = "str"; print ${*{${$main::{$pack}}{$var}}{SCALAR}}; __END__ foo str
b) You could also use string eval - but that's as deprecated as symbolic references hereabouts ;-)
use strict; $Foo::str = 'foo str'; my $class = 'Foo'; my $value = eval "\$$class\::str"; print $value,$/;
2. Look into the symbol table:
package Foo; use vars qw($str); $str = "foo str"; package main; my $pack = "Foo::"; my $var = "str"; print "$_: ",(defined ${$main::{$pack}}{$_} ? 'yup' : 'nope'),$/ for qw(str bar); __END__ str: yup bar: nope
update: Caveats about autovivification apply. You might want to break up the lookup into steps, operating with defined. Consider:
$\=$/; use strict; use warnings; package Foo; use vars qw($str); $str = "foo str"; package main; my $pack = "Bar::"; my $var = "str"; print "yup" if defined ${$main::{$pack}}{$var}; /::$/ and print for keys %main:: __END__ version:: Tie:: utf8:: re:: CORE:: DynaLoader:: mro:: strict:: attributes:: Bar:: <----here Regexp:: vars:: UNIVERSAL:: Foo:: main:: Carp:: PerlIO:: IO:: Internals:: warnings:: DB::
Symbol tables are subject to autovivification, too.
In reply to Re: How to access globals in arbitrary classes, without using soft ref?
by shmem
in thread How to access globals in arbitrary classes, without using soft ref?
by llancet
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |