Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

using 'my'

by kiat (Vicar)
on Jun 21, 2001 at 17:48 UTC ( #90351=perlquestion: print w/replies, xml ) Need Help??
kiat has asked for the wisdom of the Perl Monks concerning the following question:

is using "my" to declare variables necessary if the program (2-page long) works fine without the variables being declared with "my"? hope this is not a lame's actually my first post here :)

Edit 2001-21-06 Masem - edited title from "using"

Replies are listed 'Best First'.
(jeffa) Re: using
by jeffa (Bishop) on Jun 21, 2001 at 18:01 UTC
    Can you spot the error?
    $illusion = ''; print "$i11usion\n";
    If you run this, you get: a new line.

    However, if you use strict (and -w) you would know exactly what the problem is. Whether a program is 2 pages or 200 pages long, I'd rather not pull my hair out over such a trivial typo. But, there is always more than one way to do it - caveat programre!


      I could once I got the text into a text editor. I'd have gone for a mispelling by yours is pretty much the best case for use strict; I've seen in a while.


      <CODE> $pword = "password" ;
      print $pwords\n" ;
      print "\x{263a}"
Re: using
by damian1301 (Curate) on Jun 21, 2001 at 17:59 UTC
    You should probably check out a little article written here, Coping with Scoping.

    In the meantime, you should read about, and my.

    $_.=($=+(6<<1));print(chr(my$a=$_));$^H=$_+$_;$_=$^H; print chr($_-39); # Easy but its ok.
Re: using
by azatoth (Curate) on Jun 21, 2001 at 17:55 UTC
Re: using 'my'
by Elgon (Curate) on Jun 21, 2001 at 19:21 UTC


    Fret ye not: This is not a lame question but rather relates to an article of the faith for Perlmonks.

    The strict answer to your question (excuse the bad pun) is no, you do not need to declare the variables if you are not using the strict pragma. This means you will need to declare all of your variables using my which is generally agreed to be a good idea.

    A slightly better answer is that you should (nearly) always use strict; and preferably the -w switch or the warnings pragma too (These two are very slightly different if you're using Perl 5.6 or later, see this for more info.) If there is a good reason why you shouldn't be using strict there is probably a far better and/or safer way of doing what you are trying to do!

    There are lots of very good reasons why you should use strict; and warnings and if you are doing CGI work -T too: You will be warned about typos in your variable names because the code won't run and will give you the location of the (probable) typo, warnings will give you more useful debugging information about nonfatal errors in your code and -T, well let's just say that it can make life a more pleasant experience for everybody except anyone trying to do unpleasant things to your website. All of the links given by the other posters will be damned helpful, good luck.


    PS: Oh, and welcome to <a href="http://"">Perlmonks!

    "Without evil there can be no good, so it must be good to be evil sometimes.
    --Satan, South Park: Bigger, Longer, Uncut.

Re: using 'my'
by mr_mischief (Monsignor) on Jun 21, 2001 at 19:01 UTC
    Is it necessary to wear safety restraints when driving a car or operating machinery? I mean, if you don't plan on getting in an accident, then who needs safety equipment, right?

    What happens, though, when you are diving perfectly safely, then someone comes along and runs a light, smashing into you? Now is when you _need_ the safety belt. The problem is, it's too late to put it on.

    So, what happens when you write a perfect 10,000 line program without scoping? It's a perfect program. What happens in six months when you need to help track down a typo someone else made in the code and you don't quite recall what each of those 10,000 lines does (because you've worked on two new major projects and four major maintenance projects in the meantime, as well as daily tweaks and bug hunts)? Now is when you _need_ scoping...

Re: using 'my'
by sierrathedog04 (Hermit) on Jun 21, 2001 at 19:40 UTC
    I agree with all of those who say to 'use strict." However, using strict does not necessarily require the use of lexicals declared with my(). You may if you wish simply append main:: in front of all of your variables. That will declare your variables as global, which they already are anyway if you are not declaring them with my().

    (Side note: Perl does not have true global variables. All variables exist only in the package in which they are defined. However, because main:: is the default package, variables that are non-lexical in main appear almost as if they are global.)

    One point on 'use strict'. My brother has a magnificent e-commerce site written completely in Perl 5.00x It supports his entire family very nicely.

    He does not 'use strict'! I told him that what he was doing was 'blasphemy.' He said that he does not view using Perl as a religious act. I cannot argue with success, but I will always use strict, and where possible I convert scripts written by others to strict when I maintain them.

      Actually there are a number of truly global variables in Perl. For instance no matter what package you are in, $ENV, $^W, $_, etc are always the same.
        You are correct. Camel III's glossary says:
        In Perl, only certain special variables are truly global—most variables (and all subroutines) exist only in the current package.
        FWIW, those truly global variables are really all in the main package. The language parser acts as if those global variable names were prefixed with main:: if no package is specified, no matter what package directive is in scope at the time.

            -- Chip Salzenberg, Free-Floating Agent of Chaos

Re: using 'my'
by nietzel (Novice) on Jun 21, 2001 at 23:56 UTC
    Everyone has gave you some good replies but here is a resource that comes from, the horse's mouth, Larry Wall.

    Programming PERL 2nd Edition
    Chapter 8
    Topic "Programming with Style"

    "The most important thing is to run your programs under the -w flag at all times. You may turn it off specifically for particular portions of code via the $^W variable if you must. You should also always run under strict or know the reason why not. The use sigtrap and even use diagnostics pragmas may also prove of benefit."

    That pretty much says it all!

    Good Luck
Re: using 'my'
by tachyon (Chancellor) on Jun 21, 2001 at 22:17 UTC

    You may find some benefit in reading Use strict warnings and diagnostics for a brief ode praising the benefits of being strict. This article is a couple of pages long. If you want more detail there is a longer version as well. There are also links to all the detail you are likely to want. I highly recommend the Mark-Jason Dominus article "Coping with scoping" which has already been suggested to you.

    When your two page app becomes 1500 lines of code you will be happy you made the effort!



Re: using 'my'
by Anonymous Monk on Jun 21, 2001 at 20:16 UTC
    You don't have to 'use strict' but it certainly helps you catch those hard to see errors.

    I often use strict and declare my variables global.

    #!/usr/bin/perl -w
    use strict;
    Kind of lazy, but I can use the variables everywhere in the script and I still catch the errors. Heffa K

      I'm sorry, but those aren't global variables, they are just lexically scoped variables at the "highest level" of a script.

      Declaring variables like this is bad practice, in my mind if you're doing CGI programming, or any other perl programming that creates persistent compiled copies of perl scripts.

      This type variable sharing will give the famous "variable will not stay shared" error with mod_perl.

      If you're never going to use mod_perl, then you can keep on coding this way. A better way would be to pass all variables to your subroutines as arguments, thusly:

      first_sub('Testing, testing',' one, two, three'); sub first_sub { my ($var,$var2)=@_; second_sub($var,$var2); } sub second_sub { my ($variable,$variable2)=@_; print $variable.$variable2; }

      This more rigid, but it really helps you keep your variables in line, making for easier maintaince down the road. You can reuse the subroutine elsewhere, 'cuz you know exactly what goes in and what comes out.

      You could declare the variables as globals with the closed perl equivalent, thusly:

      use strict; use vars qw/$var1 $var2/;

      but this is bad programming practice generally, as I understand it. (why is this? Is it due strictly to memory usage?)

      Update: Of course. I must have had a brain cramp. See TGI's post below.

        Hero Zzyzzx said: You could declare the variables as globals...but this is bad programming practice generally, as I understand it. (why is this? Is it due strictly to memory usage?)

        You answered your own question as to why globals are bad, when you said You can reuse the [code] elsewhere, 'cuz you know exactly what goes in and what comes out. It has to do with modularity of code. It's a lot easier to make everything global and share data around indiscriminantly, but maintaining such code can be hellish.

        Perl, more than any other language I've used, gives you the flexibility to 'get stupid.' That's what makes Perl so great, sometimes you just need to get something done, and its easier and faster to do it if you do it 'the wrong way'.

        TGI says moo

Re: using 'my'
by chorg (Monk) on Jun 22, 2001 at 00:37 UTC
    Use it always, unless you are writing a one liner in the shell. It is your friend...
    "Intelligence is a tool used achieve goals, however goals are not always chosen wisely..."
      thanks everybody for responding! i didn't realise there were so many replies until today. there were all very helpful, thanks once again and cheers :)