我知道我可以列出所有的包和lexcial变量在使用某个特定范围Padwalker的peek_our和peek_my,但我怎么能得到像全局变量的名称和值$"和$/?
#!/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;
}
Run Code Online (Sandbox Code Playgroud)
fid*_*ido 32
您可以访问符号表,查看p."Perl编程"的第293页另请参阅"掌握Perl:http://www252.pair.com/comdog/mastering_perl/ 具体:http://www252.pair.com/comdog/mastering_perl/Chapters/08.symbol_tables.html
您正在寻找的那些变量将位于主命名空间下
谷歌快速搜索给了我:
{
no strict 'refs';
foreach my $entry ( keys %main:: )
{
print "$entry\n";
}
}
Run Code Online (Sandbox Code Playgroud)
你也可以
*sym = $main::{"/"}
Run Code Online (Sandbox Code Playgroud)
同样适用于其他价值观
如果你想找到你可以做的符号类型(从掌握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};
}
Run Code Online (Sandbox Code Playgroud)
就是这样.感谢MGoDave和kbosak在我面前提供答案,我看起来太傻了(我看着%main ::开始,但错过了他们没有他们的印记).这是完整的代码:
#!/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);
for my $name (keys %main::) {
my $glob = $main::{$name};
if (defined ${$glob}) {
$in_scope{'$' . $name} = ${$glob};
}
if (defined @{$glob}) {
$in_scope{'@' . $name} = [@{$glob}];
}
if (defined %{$glob}) {
$in_scope{'%' . $name} = {%{$glob}};
}
}
#lexicals hide package variables
while (my ($var, $ref) = each %$lexical) {
$in_scope{$var} = $ref;
}
return \%in_scope;
}
Run Code Online (Sandbox Code Playgroud)
您可以执行以下操作来检查主程序包的符号表:
{
no strict 'refs';
for my $var (keys %{'main::'}) {
print "$var\n";
}
}
Run Code Online (Sandbox Code Playgroud)