Is there a built-in function to clear all variable values

谁都会走 提交于 2019-12-05 12:31:36

As mentioned in other answers, your request speaks to a larger problem with the design of your program. You should either use lexicals that will fall out of scope, or closely manage all of your global arrays, and create a function that will clear them for you.

If you insist on bludgeoning every array in your namespace, at least take care and check to make sure you aren't writing over values that Perl may need:

for (keys %::) {  # for everything in `package main;`
    if (*{$::{$_}}{ARRAY}) {  # if there is an array in the slot
        # clear it unless it is a "special" array
        @{$::{$_}} = () unless /^(?:INC|ISA|EXPORT|EXPORT_OK|ARGV|_|\W)$/
    }
}

I would write it like this though:

my @global_arrays = \our (@foo, @bar, @baz);
sub clear_global_arrays {
    @$_ = () for @global_arrays
}

The effect is the same for the arrays in question, yet it does not run the risk of clobbering anything you did not intend to. You could even use my rather than our with the second example, whereas the first example requires the variables to be in the symbol table (aka defined with our).

Don't use global arrays. It's as simple as that. Lexical arrays are limited to the scope where they are declared, and automatically start empty when you enter the scope.

If you must use globals, keeping track of them all in one place is a good idea anyway, so clearing them shouldn't be difficult.

Someone once posted an now-infamous tool to perlmonks to do what you want. The code was withdrawn after receiving much criticism of the whole idea; you can read some of the criticism here: http://www.perlmonks.org/index.pl?node_id=349496

The fact that you want this screams "bad design" to me. However, on the assumption that you know exactly what you're doing with this radioactive chainsaw, you can accomplish it by accessing the global symbol table hash %:: or %main::. (The colons are part of the name.) This hash contains a mapping from every defined global symbol to a reference to its variable.

Something like this should suffice:

for my $ref (values %::) {
    @{$ref} = ();
}

Edited to remove the check against array references. All of the values are in fact typeglob references, so there's no need to check.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!