Reputation: 620
I need to reset some global hash variables in a mod_perl script.
This works - as described e.g. here: https://stackoverflow.com/a/4090870
$_ = '' for ($a, $b, $c);
$_ = 0 for ($d, $e, $f);
This doesn't seem to work:
$_ = () for (%a, %b, %c);
Why doesn't it work with hashes? Can it be done? What about with arrays?
(I do normally try to scope variables so the above is not necessary, but in this case, I am afraid it will have to be like this. Also, I may be missing some basic understanding of how for...each loops work in Perl, please enlighten me.)
Upvotes: 3
Views: 171
Reputation: 34130
You're doing more work than you have to. There is no need to loop over the variables.
$_ = '' for ($a, $b, $c);
$_ = 0 for ($d, $e, $f);
($a,$b,$c) = ('') x 3; # ... = ('','','')
($d,$e,$f) = (0) x 3; # ... = (0,0,0)
Of course it would be easier if you wanted to set them to undef
($a,$b,$c) = (); # set them to undef
The only reason to loop over the variables is if you were doing it in a subroutine on behalf of some other scope.
sub fill{
my $fill = shift;
$_ = $fill for @_;
return;
}
{
fill( 0, my($d,$e,$f) ); # my($d,$e,$f) = (0) x 3;
}
Similarly, instead of going through a list of hash refs:
%$_ = () for \(%a, %b, %c);
# or
%$_ = () for (\%a, \%b, \%c);
Just set them to the empty list.
(%a,%b,%c) = ();
You should only rarely need to do this, if you set the scope of the variables correctly.
my(%a,%b,%c); # <== wrong
sub exmpl{
(%a,%b,%c) = (); # <==
# do something with them
...
}
sub exmpl{
my (%a,%b,%c); # <== correct
# do something with them
...
}
Upvotes: 3
Reputation: 12393
You could do it with references:
%$_ = () for (\%a, \%b, \%c);
but this does not answer your question as to why it doesn't work without references:
When putting a hash into your for (%h)
-statement the hash is evaluated implicitly in list context.
(EDIT: I was initially said scalar context and realized later it is list context and adapted the answer)
Upvotes: 4