in reply to Can't localize lexical variable $var at...

The docs are pretty clear on this--you can only localize global variables.

This is partially for hysterical raisins, as global variables and local predated lexicals by quite a bit in perl's history. Local is a hackish way to implement lexical scope without lexical variables.

There's also little reason to use local with a lexical--since local overrides a variable until the end of the scope, you might as well either overwrite the lexical (if it's in the scope the lexical was declared) or my a new version of the lexical (if it's in an inner scope from the declaration).

  • Comment on Re: Can't localize lexical variable $var at...

Replies are listed 'Best First'.
Re: Re: Can't localize lexical variable $var at...
by shotgunefx (Parson) on Jun 10, 2002 at 06:46 UTC
    Just for completeness, you can localize an element of a lexical hash or array. How useful this is, I don't know.
    #!/usr/bin/perl use warnings; my %hash = (a=>1, b=>2); { local $hash{'a'} = 999; print map {"$_ = $hash{$_}, "} sort keys %hash; print "\n"; } print map {"$_ = $hash{$_}, "} sort keys %hash; print "\n";
    I've always been a little confused as to why this was implemented for elements of a lexical hash or array but not scalar

    -Lee

    "To be civilized is to deny one's nature."
      That's one of the things that slipped in under the radar. There's no real difference between elements of a lexical and global array or hash, so you can localize either with no penalty. It's a quirk of the implementation--whether it's a bug or not is arguable. (local's already got a number of problems, mainly when localizing anything with magic)