Why is the default scoping behavior in Perl the way that it is?
Asked Answered
B

3

5

I am learning Perl for school, and currently am learning about the use of the my keyword and about scoping in Perl. (For reference, I was looking at How should I use the "my" keyword in Perl? .) Hopefully this question hasn't already been asked elsewhere, but if not...why is Perl's default behavior the way that it is?

It seems to me that a C-style default scoping makes the most sense...you declare a variable inside a block, the variable exists inside that block, and once you leave that block, that variable is no longer accessible. Why is it that in Perl, to specify this behavior, you must use the my keyword? It seems that limiting a variable's scope to only where it is used would be good standard behavior, and using my all the time seems to be very redundant and like it would contribute to cluttering of code.

Seems a bit like walking in to the grocery store and immediately loudly declaring your preferred brand of such-and-such before continuing with your shopping, just in case anyone around you was curious (which they probably weren't).

(Potential duplicate, this question might get taken down... Why declare Perl variable with "my" at file scope? .)

Bivens answered 9/12, 2020 at 23:2 Comment(4)
Short answer: backward compatibility. Before perl had "my", it had variables with different behaviors.Tagliatelle
What other keyword would you prefer to declare a variable?Dreibund
See also A short whishlist of Perl5 improvements leaping to Perl7 at PerlMonks.Dreibund
Just personal thoughts; with my you can see intention of variable declaration vs. variable (re)assignment. This enables warnings of duplicate vars when declaring inside the same block (which is IMO a good thing). As a side note, javascript behaves in the same manner.Suckerfish
C
9

If you want lexically-scoped variables, you need some form of declaration.[1]


It seems to me that a C-style default scoping makes the most sense...you declare a variable inside a block, the variable exists inside that block, and once you leave that block, that variable is no longer accessible

That's exactly how it works in Perl. Where one would declare a variable using int i in C, one uses my $i in Perl. Both create a lexically-scoped variable, which is to say a variable which is only visible in the current block and contained blocks. When executing code outside of the block, the variable is not accessible. The scope of variables in Perl is the same as the scope of variables in C.[2]

// Can't use `i` here.           # Can't use `$i` here.
{                                {
   // Can't use `i` here.           # Can't use `$i` here.
   int i = 4;                       my $i = 4;
   printf("%d\n", i);       4       say $i;
   {                                {
      printf("%d\n", i);    4          say $i;
      int i = 5;                       my $i = 5;
      printf("%d\n", i);    5          say $i;
   }                                }
   printf("%d\n", i);       4       say $i;
}                                }
// Can't use `i` here.           # Can't use `$i` here.

  1. Python doesn't have explicit variable declarations, but it also doesn't have lexically-scoped variables; Python variables are function-scoped.

  2. However, the lifetime of variables isn't the same. A scalar can be kept alive past the end of the block in which it resides in Perl, but that's not the case for similar variables in C (variables with "automatic storage duration").

    For example,

    # You can't use `@a` outside of the sub,
    # But you can use the created array anonymously.
    sub f { my @a = qw( abc def ); return \@a; }
    

    In that sense, my $x is more akin to a dynamically allocated struct.

Corduroys answered 9/12, 2020 at 23:30 Comment(0)
Z
6

Because that's how Larry Wall did it in 1987 and Perl 5 remains backwards compatible with that decision. Lexical variables were not introduced until Perl 5 in 1994 and by then there was quite a large install base of Perl 4 programs.

I'll speculate why. Perl was not conceived as an application language, it became one. Perl 1 was written in 1987 as a more powerful alternative to sed, awk, and Bourne shell.

If you have a problem that would ordinarily use sed or awk or sh, but it exceeds their capabilities or must run a little faster, and you don’t want to write the silly thing in C, then perl may be for you.

From the Perl 1.0 manual.

sed and awk programs are usually just one line. And in shell variables are global. Given the purpose of Perl 1, that was just fine.

Accepted software engineering standards have changed a lot in the last few couple decades. Back when systems were smaller and simpler, global variables were more acceptable. As complexity has grown, global variables are increasingly a hazard.

Zacarias answered 10/12, 2020 at 0:0 Comment(2)
sed and awk programs are usually just one line -- is a little bit stretch. I've seen some quite complicated programs written in awk/nawk and not so complicated written in sed. Of cause sed, awk was never intended for creating application.Athalee
That makes sense. Knowing the background (early history) of Perl as an alternative to sed/awk/sh, I can see how it develops that way. I suppose at some point, somebody said "Hey, what if I want non-global variables?" and they came up with a way to do that (the my keyword) that still allowed backward compatibility.Bivens
F
1

Strictly speaking, the default scoping of variables in Perl is the package global. Variables that do not have to be declared. That tells you a lot about Perl's philosophy. It's task oriented and excels at rapid prototyping and quick and dirty programming. You can write complete programs on the command line to do rather complex tasks (perl -e). Only a masochist would do perl -e 'use strict; ...'. You just write variables and they just work. One of those philosophies is DWIM - do what I mean. That's the complete opposite of most "hard" programming languages where you have to define the world before you can do anything.

Then in Larry's good time we got strict, use vars, my, our, and state to complete the management of variables. They work for us, not the other way around. In fact it can be considered rude programming to not put certain data in globals. Because I don't necessarily know better than the next guy and if he wants to introspect or modify my code or module, that's just fine and neighborly.

Here are some very instructive links to talks given by Larry Wall, Perl's creator.

Perl, the first postmodern computer language

The Culture of Perl

Seriously though, if there’s a germ of an important idea in Perl Culture, it’s this: that too much control is just as deadly as too little control. We need control and we need chaos.

Programming is Hard, Let's Go Scripting...

The frustrations of Unix shell programming led directly to the creation of Perl. I found that shell scripting was intrinsically limited by the fact that most of its verbs are not under its control and the nouns are impoverished, restricted to strings and files, with who-knows-what typology. I don’t want to talk to a stupid computer language. I want my computer language to understand the strings I type.

For more, visit perl.com

Filmore answered 12/12, 2020 at 4:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.