in reply to nuances of my, and maybe local

To answer your question on local, it makes a temporary copy of a higher-scoped variable. For example:

my $fred = "foo"; for (my $idx = 1; $idx <= 10; $idx++) { local $fred; $fred = $fred x $idx; print $fred, "\n" # foo, foofoo, foofoofoo... } print $fred, "\n"; # foo

So once your for loop is done, even though you kept modifying fred each time, at the end of the loop, fred is still "foo".

EDIT: Apparently my understanding of local was not correct. Live and learn. If somone would delete this post I would appreciate it.

Replies are listed 'Best First'.
Re: Re: nuances of my, and maybe local
by diotalevi (Canon) on Sep 27, 2002 at 17:35 UTC

    Samurai, local() operates on things that live in the symbol table - lexicals don't and you can't local()ize a lexical. You *can* use nested my() calls but that's almost always the wrong thing.

    # This prints: # Lexicals: 12 # Globals: 34 use strict; # nested my() example my $lex = 1; { # local $lex; this line is a syntax error my $lex = 2; print "Lexicals: $lex "; } print "$lex\n"; # local()ized global our $global = 3; { local $global; $global = 4; print "Globals: $global "; } print "$global\n";
Re: Re: nuances of my, and maybe local
by shotgunefx (Parson) on Sep 27, 2002 at 17:31 UTC
    local works on package variables and lexical hash elements only.
    my $foo; local $foo # WRONG my %foo; local %foo; # WRONG my %foo; local $foo{key} = 'value'; # OK use vars qw ($var); $var=5; local $var = 10; # OK


    -Lee

    "To be civilized is to deny one's nature."
      Wrong.

      local doesn't care whether the hash is lexical, it can replace array elements, and the only reason it doesn't work on lexical variables is that Larry ruled that too confusing.

        You are correct. Need more sleep

        -Lee

        "To be civilized is to deny one's nature."
Re: Re: nuances of my, and maybe local
by Helter (Chaplain) on Sep 27, 2002 at 17:32 UTC
    I tried to run that code, and got:
    ./test.pl Can't localize lexical variable $fred at ./test.pl line 7. Exit 255
Re: Re: nuances of my, and maybe local
by Helter (Chaplain) on Sep 27, 2002 at 17:39 UTC
    my $fred = "foo"; for (my $idx = 1; $idx <= 10; $idx++) { #Changed this line to my my $fred = "blah"; # $fred = $fred x $idx; print $fred, "\n" # foo, foofoo, foofoofoo... } print $fred, "\n"; # foo

    Outputs:
    ./test.pl blah blahblah blahblahblah blahblahblahblah blahblahblahblahblah blahblahblahblahblahblah blahblahblahblahblahblahblah blahblahblahblahblahblahblahblah blahblahblahblahblahblahblahblahblah blahblahblahblahblahblahblahblahblahblah foo
    So it looks like my will at least hide the value of the outer scope's version of $fred. More confusion, I have not read the links below yet.....

    Thanks!