Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^5: A short whishlist of Perl5 improvements leaping to Perl7 (Thought Experiment No.2)

by LanX (Saint)
on Nov 28, 2020 at 12:48 UTC ( [id://11124319]=note: print w/replies, xml ) Need Help??


in reply to Re^4: A short whishlist of Perl5 improvements leaping to Perl7 (Thought Experiment No.1)
in thread A short whishlist of Perl5 improvements leaping to Perl7

While the former thought experiment was closer to Python's behavior - all vars belong (mostly) to function scope - there is another possible approach.

1. any assignment to a new variable leads to an implicit my but only if their was no previous explicit declaration in a surrounding scope. This will replace former rules 1,4 and 5 all others still apply

Hence we get the following 4 cases for explicit declarations with my or our

automine effect comment
{ $x = 1; { $x = 2; } }
{ my $x = 1; { my $x = 2; } }
not strict w/o automine
{ $x = 1; { my $x = 2; } }
{ my $x = 1; { my $x = 2; } }
not strict w/o automine
{ my $x = 1; { $x = 2; } }
{ my $x = 1; { $x = 2; } }
backwards compatible
{ my $x = 1; { my $x = 2; } }
{ my $x = 1; { my $x = 2; } }
backwards compatible

Surprises and pitfalls:

automine effect comment
sub foo { if (1) { $x = 2; } print $x; }
sub foo { if (1) { my $x = 2; } print $x; # undeclared }
Doesn't compile

Surprising for Pythonistas

sub add { $x = 0; for (1..9) { $x = $x + $_; } print $x; }
sub add { my $x = 0; for (1..9) { my $x = $x + $_; } print $x; # prints 0 }
Unexpected result!

Needs an explicit my $x = 0 at init to avoid implicit my

This is a very Perlish approach and avoids many edge cases.

Of course this laziness comes with a price, introducing a new explicit declaration on file scope has an effect at the distance and could silently break subroutines

use automine # our $var; ... sub foo { $var = shift; # not 'my $var' if explicit 'our $var' exists ... }

That's why this theoretical pragma must be optional. (Of course scoping the our inside a tight block would also prevent this.)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

  • Comment on Re^5: A short whishlist of Perl5 improvements leaping to Perl7 (Thought Experiment No.2)
  • Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11124319]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-04-25 17:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found