如何列出给定范围内的所有变量? [英] How can I list all variables that are in a given scope?
问题描述
我知道我可以使用 Padwalker
的peek_our
和peek_my
,但是如何获取所有全局变量(如$"
和$/
)的名称和值?
I know I can list all of the package and lexcial variables in a given scope using Padwalker
's peek_our
and peek_my
, but how can I get the names and values of all of the global variables like $"
and $/
?
#!/usr/bin/perl
use strict;
use warnings;
use PadWalker qw/peek_our peek_my/;
use Data::Dumper;
our $foo = 1;
our $bar = 2;
{
my $foo = 3;
print Dumper in_scope_variables();
}
print Dumper in_scope_variables();
sub in_scope_variables {
my %in_scope = %{peek_our(1)};
my $lexical = peek_my(1);
#lexicals hide package variables
while (my ($var, $ref) = each %$lexical) {
$in_scope{$var} = $ref;
}
##############################################
#FIXME: need to add globals to %in_scope here#
##############################################
return \%in_scope;
}
推荐答案
您可以访问符号表,签出p. "Programming Perl"的293 另请参阅"Mastering Perl: http://www252.pair.com/comdog/mastering_perl/ 具体来说: http://www252.pair.com/comdog/mastering_perl/章/08.symbol_tables.html
You can access the symbol table, check out p. 293 of "Programming Perl" Also look at "Mastering Perl: http://www252.pair.com/comdog/mastering_perl/ Specifically: http://www252.pair.com/comdog/mastering_perl/Chapters/08.symbol_tables.html
您要查找的变量将位于主命名空间下
Those variables you are looking for will be under the main namespace
快速的Google搜索给了我
A quick Google search gave me:
{
no strict 'refs';
foreach my $entry ( keys %main:: )
{
print "$entry\n";
}
}
您也可以
*sym = $main::{"/"}
以及其他值
如果要查找符号的类型,可以做(通过掌握perl):
If you want to find the type of the symbol you can do (from mastering perl):
foreach my $entry ( keys %main:: )
{
print "-" x 30, "Name: $entry\n";
print "\tscalar is defined\n" if defined ${$entry};
print "\tarray is defined\n" if defined @{$entry};
print "\thash is defined\n" if defined %{$entry};
print "\tsub is defined\n" if defined &{$entry};
}
这篇关于如何列出给定范围内的所有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!