in reply to Difference b/w my and local var?

Both of them are used to declare local variables.

The variables declared with "my" can live only within the block it was defined and cannot get its visibility inherited functions called within that block, but one defined with "local" can live within the block and have its visibility in the functions called within that block.

Replies are listed 'Best First'.
Re^2: Difference b/w my and local var?
by moritz (Cardinal) on Mar 11, 2009 at 15:35 UTC
    Both of them are used to declare local variables

    No. local does not declare a variable, as you can easily try out:

    $ perl -Mstrict -e 'local $x' Global symbol "$x" requires explicit package name at -e line 1. Execution of -e aborted due to compilation errors.

    If local declared a variable you wouldn't get an error message here.

      Yikes!! More fun with definitions...

      What does "declare" mean and what does "local" mean?

      strict says of "strict vars":

      This generates a compile-time error if you access a variable that wasn’t declared via "our" or "use vars", localized via "my()", or wasn’t fully qualified.

      If "localized via "my()"" is reasonable terminology, then surely it is reasonable to say that as a result the variable is "local". And surely "local" creates a "local" variable. So it is no wonder that the gentle reader has concluded that both "my" and "local" produce "local" variables and that the declarative statements "my $var" and "local $var" both "declare" them to be "local".

      It is most unfortunate that there is so much loose use of terminology.

      What your example shows is that, consistent with the documentation of "strict vars", "local $var" does not "declare" the variable in a manner that satisfies the requirements of "strict vars" and that without them being satisfied an unqualified reference to the variable produces an error. The variable is none the less localized (declared to be local???) in the absence of "strict vars" and can be localized with "strict vars" in effect by using its fully qualified name.

      Consider

      #!/usr/bin/perl -w use strict; use warnings; use Devel::Peek; $main::x = 10; { local $main::x = 20; print "$main::x\n"; } print "$main::x\n";

      Which produces

      20 10

      In this example, is it reasonable to say that $x has not been "declared to be local" just because it has not been declared in a manner that satisfies "strict vars" so that it can be referenced by its unqualified name?

Re^2: Difference b/w my and local var?
by anbutechie (Sexton) on Mar 11, 2009 at 13:34 UTC
    Thank you very much. I got it.
    Regards,
    Anbarasu