in reply to Make $^V and "my" implicit

So what does the following code output?

no my; $user= 'World'; sub greet { print "Hello, $user"; }; greet();

Before you answer, compare this to the two Perl programs that reduce to the same code:

use strict; my $user= 'World'; sub greet { my $user; print "Hello, $user"; }; greet();
use strict; my $user= 'World'; sub greet { print "Hello, $user"; }; greet();

Replies are listed 'Best First'.
Re^2: Make $^V and "my" implicit
by gunzip (Pilgrim) on Feb 03, 2014 at 17:47 UTC

    "my" or it's equivalent should only be necessary in the not-so-common case where you have 2 variables with the same name and type ($@%). Why is "my" even necessary for the global declaration of $user in your example? "my" should only be necessary for the function-level $user variable in your case and, as a general rule, only necessary when distinguishing variables which have the same name and type ($@%).

    Perl shoud apply rules such as these in a more fine-grained manner instead of peppering code with redundant scoping declarations. However, I am not arguing against the principle of "my" in general.

      But if that case is not-so-common, then you don't need my at all.

      my forces you to predeclare variables. This is highly important, as Perl can then tell you if you misspell a variable.

      It has the additional advantage of allowing you to explicitly declare the scope of a variable, to tell Perl whether you meant to create a new, lexically scoped variable or whether you meant to use the global variable.

      I think most of your complaints can be done away with by not using strict. Then you don't need to predeclare your variables but still can use lexical variables with my. Of course, recursion is a harsh mistress if you're using global variables. Typos also are a nasty problem. But you don't seem to have these.

        I'm aware you do need a way of distinguishing variables of the same type and name used in different scopes but "my" just seems to over-generalise the issue to the point that it becomes boilerplate. Depends on your view at the end of the day, I suppose.
      A reply falls below the community's threshold of quality. You may see it by logging in.