11.4. Must I use "my" on all my variables?

If you use strict; (as recommended) the answer is "probably". This confines the variables names to your namespace - so your variable does not conflict with one in the module(s) your are using (you are at the least useing Tk;). my does "lexical scoping" on a variable rather than the "dynamic scoping" done by local (like auto variables in C). The difference between these two is that the scope of my $var is confined to the block (sub, if, foreach, etc.) in which it is declared and used, as opposedto local $iable which can propogate to all blocks called by the block in which it is declared. In general the confined scope of my $var means that its use will proceed quicker and more efficiently than local $iable.

If you give a fully qualified variable name such as

    $main::var = 1;  # No "my" needed
Then no my $var is needed. However, the lexical scoping of my $var makes it preferable.

If you choose to use my (as recommended) then beware that you should declare a variable my only at the first use (instantiation) of a variable. Consider yet another way to re-write the "Hello World!" script:

    #!/usr/local/bin/perl -w
    use strict;
    use Tk;
    my $main = new MainWindow;
    my $label = $main->Label(-text => 'Hello World!');
    my $button = $main->Button(-text => 'Quit',
                               -command => sub{exit});
    $label->pack;  #no "my" necessary here
    $button->pack; #or here
    MainLoop;
Considering the finite number of names (in particular the high probability that a variable named $label or $button was used in one or more of the extensions to perl that you may be using) it helps one's programming to use strict; and declare variables yours alone with my.

James M. Stern points out that redundant my declarations are not simply useless they can be dangerous as in the following script which will not work:

    #!/usr/local/bin/perl -w
    use strict;
    use Tk;
    my $main = new MainWindow;
    my $label = $main->Label(-text => 'Hello World!');
    my $main;   #WRONG: this $main overrides previous
    my $button = $main->Button(-text => 'Quit', #will now fail
                               -command => sub{exit});
    $label->pack;  
    $button->pack; 
    MainLoop;

Previous | Return to table of contents | Next