Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello fellow Monks!
I have a rather newbie question...
If you have a code that runs perfectly fine, do you get more speed or something else if you use "my" and, in general, write the code more strictly?
Of course I know it should be with "my" etc, I am just wondering if there is another reason behind it except writing clean code.

Replies are listed 'Best First'.
Re: Question on "my" in the variables
by davido (Cardinal) on Feb 25, 2014 at 00:06 UTC

    strict does exactly three things: use strict 'refs'; causes a runtime error if you attempt to use symbolic references. use strict 'vars'; generates a compiletime error if you attempt to access a variable that was neither predeclared nor fully qualified.. use strict 'subs'; generates a compiletime error if you attempt to use a bareword that is not a subroutine name or filehandle (a slight oversimplification). use strict; gives you all three of those behaviors, and that's generally the minimum standard that modern Perl users prefer to code to.

    The reason for using "my" (lexical) variables is that they facilitate compartmentalization and scoping, which are fundamental principles for structured programming. If you wish to enjoy the benefits provided by structured programming principles, you will appreciate that 'strict' helps you to enforce the use of lexically scoped variables. Regardless of whether you want to use compartmentalization techniques, you should still enjoy the benefit that enforced pre-declaration of variables provides in preventing typos from going undiscovered until a bug turns up.

    A significant step toward becoming a good programmer is learning discipline. It may seem easy to pass values around a script globally, to not bother with parameter passing, and so on. ...and for fifteen or so lines of code, that probably is easier (unless doing so goes so much against habit that it feels harder). But for some number of lines of code greater than fifteen or so, the spaghetti nightmare that comes with undisciplined programming techniques will begin to make the task much harder than it needs to be. It turns out that developing good habits early on helps to make simple things easy, and hard things possible, which is a primary goal of programming with Perl.

    Even someone who doesn't care about becoming a "good programmer" should care about putting more effort into something than necessary. Good programmers have learned that discipline reduces the overall effort required to accomplish any non-trivial programming task. The fact that discipline makes the job easier is universally applicable; it works not only for good programmers, but also for novices -- novices often just don't realize that it can help, and consequently end up working too hard.

    So this is your moment! Take that first step toward making the task easier; program with discipline; use strict;. (But equally important, learn why you are using it.)


    Dave

Re: Question on "my" in the variables
by einhverfr (Friar) on Feb 25, 2014 at 04:14 UTC

    I am going to add another reason to use "my" and that is testing.

    Here is my background. I am a core maintainer of LedgerSMB and as such we have a lot of legacy code we inherited from SQL-Ledger, which almost never lexically scopes variables. If left alone the code works ok most of the time, but it is relatively brittle and it cannot be tested because of sloppy scoping. Our focus is mostly in removing this code and replacing it with something more manageable.

    Lexically scoping variables is a prerequisite for being able to sanely write test cases. Very often times you really need to be able to make repeated function calls in ways you might not necessarily want to do in the general operation of your application. Without lexical scoping, the variables are not reset on function call and consequently things like running totals in reports keep on running. Managing this in a test case is a mess.

    I personally spent 8 hours one day working on getting a single report we inherited to pass automated test cases. The report, mind you, passed *manual* test cases consistently, but the sloppy scoping meant that automated test cases invariably failed on second and subsequent runs.

    Without automated test cases, you can't ever be really sure that code contracts you specify today will be upheld in future versions even if you don't intend to change them. Without thinking through variable scope, you can't have automated test cases. So scope your variables and scope them as tightly as you can.

Re: Question on "my" in the variables
by LanX (Saint) on Feb 24, 2014 at 23:41 UTC
Re: Question on "my" in the variables
by dsheroh (Monsignor) on Feb 25, 2014 at 09:14 UTC
    The way you phrase your question gives me the impression that you see strict/my primarily as a tool for making things look nicer and easier for humans to read.

    It is not.

    Its primary purpose is to catch your mistakes before they can cause problems. Some of those mistakes can be quite subtle. Subtle enough that, if your "code that runs perfectly fine" is anything non-trivial, strict is likely to reveal some issues that you simply haven't noticed yet.

Re: Question on "my" in the variables
by Anonymous Monk on Feb 24, 2014 at 23:41 UTC

    If you have a code that runs perfectly fine, do you get more speed or something else if you use "my" and, in general, write the code more strictly?

    my isn't magic, it doesn't make code run faster (maybe its half of a half of a half nanosecond faster if you're doing a million variables ... maybe )

    Of course I know it should be with "my" etc, I am just wondering if there is another reason behind it except writing clean code.

    clean code is the reason for 8/10 of the things you should be doing

    Chances what you think is code runs perfectly fine probably isn't that fine with or without my -- this is like every new programmers experience :)

    Have you read all these? Tutorials: Variable Scoping in Perl: the basics,
    Coping with Scoping , Mini-Tutorial: Perl's Memory Management,
    Lexical scoping like a fox,

      Actually access to the pad (i.e. where lexical variables are stored) is about 40% faster than access to the stash (i.e. where package variables are stored).

      The issue is not so much about declaring a million variables, but accessing a few variables a million times. For example, if you're finding the average of a few million small numbers, you may notice the difference between package variables and lexicals.

      Though I agree that speed is not usually the main reason for preferring lexical variables over package variables. The avoidance of action at a distance is generally the most important.

      use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
Re: Question on "my" in the variables
by locked_user sundialsvc4 (Abbot) on Feb 25, 2014 at 01:51 UTC

    Simply stated, “the real objective here is:

    When you are about to shoot yourself in the foot(!!) ... it is much better for the computer to go ‘click’ than to go ‘BANG!!’.

    If you “simply” declare all variables to be global, then the ever-accommodating “I presume that you know what you are doing” Perl language will generally try its best to accommodate you.   However, you probably would much prefer that it should detect as many of your errors as possible.   Instead of telling Perl that variables should have the widest possible scope, you probably want to be as specific as possible, and then to use strict; use warnings; so that the computer will have the greatest possible chance of detecting your unintended screw-ups.   Instead of letting Perl run amok, let Perl decline to run your code at all.

    Execution-speed is really not the point:   no one is in a hurry to get the wrong answers (or, far worse, “unexplainable but obviously-wrong behaviors”) quickly.

      ... or far, far, far worse, apparently correct behavior that is only discovered (and discovered, inevitably, in full view of your colleagues/boss/client/the world) to be wrong after a program has run for weeks or months and corrupted some vital database or transaction history that can only be corrected with vast effort and expense — if you're lucky and it can be corrected at all!