in reply to my $scope as the default for variables
in thread Please help me print this hash.

Is there any way to set my as the default scope for variables when no scope is specified?

No, not that I'm aware, though it might be possible to add that functionality (cpan://Method::Signatures).

Why isn't this the case now?

1) tradition and backwards compatibilty (perl goes back to 1987) 2) nobody's done the work ( even Method::Signatures is only since 2007 )

  • Comment on Re: my $scope as the default for variables

Replies are listed 'Best First'.
Re^2: my $scope as the default for variables
by Corion (Patriarch) on Jun 19, 2012 at 08:20 UTC

    Also, a major part of needing to predeclare your variables is to avoid typos. Having default-lexical scope avoids a lot of the nasty action-at-a-distance that default-global scope produces, but it still can't detect the typo between $outfile and $out_file for you, which I consider the major point of using strict.

      :) I was going to list this as a reason, but I remembered warnings

      $ perl -Mwarnings -e " $foo = 1; " Name "main::foo" used only once: possible typo at -e line 1. $ perl -Mwarnings -e " my $foo = 1; "

      If warnings can detect this I see no reason a New pragma 'scope' to change Perl's default scoping couldn't do the same

      Naturally that won't help if you're making the typo twice, but neither does strict/my :)

        Yes, but turning a single use of a lexical variable into a warning will raise warnings for code like:

        use Guard; sub foo { $guard = scope_guard { print "done\n" }; ... do stuff, without ever mentioning $guard again ... };

        This could maybe circumvented by only raising the warning when my is missing:

        use Guard; sub foo { # This will warn $guard = scope_guard { print "done\n" }; ... do stuff, without ever mentioning $guard again ... };

        Detecting this will be tricky, but it should catch most of the typos that would get a warning.