gpt4 book ai didi

perl - 如何列出给定范围内的所有变量?

转载 作者:行者123 更新时间:2023-12-03 08:48:29 25 4
gpt4 key购买 nike

我知道我可以使用 Padwalker peek_ourpeek_my列出给定范围内的所有package和lexcial变量,但是如何获得$"$/这样的所有全局变量的名称和值呢?

#!/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
另请参阅“掌握Perl:http://www252.pair.com/comdog/mastering_perl/
具体来说:http://www252.pair.com/comdog/mastering_perl/Chapters/08.symbol_tables.html

您要查找的那些变量将位于主命名空间下

快速的Google搜索给了我:

{
no strict 'refs';

foreach my $entry ( keys %main:: )
{
print "$entry\n";
}
}

你也可以
*sym = $main::{"/"}

同样对于其他值

如果要查找符号的类型,可以做(通过精通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};
}

关于perl - 如何列出给定范围内的所有变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/747521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com