in reply to 'use strict' Rejecting Local Hash

local doesn't actually create a local variable. That's what my does.

At least, that's what perlsub says.

Here's what I tried:

#!/usr/bin/perl -w use strict; # local %hash; # gives error my %hash; # no error { local %hash; # no error, if %hash previously declared with my # local %hash; # error if %hash previously undeclared }
local and my are completely different. What local does is, within its scope, save the previous value of a defined variable, restoring it when you leave the enclosing scope. Dominus has a nice article on the uses of local, and I'll see if I can find it before someone else posts a pointer.

Update: chipmunk and tilly are both right. I should have put use vars ( %hash ); instead of my. But the main point still stands.

Replies are listed 'Best First'.
Re: Re: 'use strict' Rejecting Local Hash
by chipmunk (Parson) on Dec 28, 2000 at 08:35 UTC
        local %hash;    # no error, if %hash previously declared with my Actually, if %hash has previously been declared with my, that will generate an error: Can't localize lexical variable %hash ... Lexical variables cannot be localized. local() doesn't have a lexical effect, so it wouldn't really make sense if they could.
      Actually lexical variables can be localized.
      use strict; my %hash = qw(hello world); print "$hash{hello}\n"; { local $hash{hello} = "WORLD"; print "$hash{hello}\n"; } print "$hash{hello}\n";
      There is no technical reason why this isn't doable for the original hash as well. The only reason why it cannot currently be done is that it is considered a likely cause of confusion.