[oak perl] still clueless about "my"

Kester Allen kester at gmail.com
Fri Feb 4 15:06:19 PST 2005


To  add my $.01 to the excellent advice already offered,  using "my"
and strict will protect commonly-named variables.   Suppose you have
two variables named "$factor", one in the main body, and one in a
subroutine, like this:

use strict;

my ( $a_number, $factor ) = ( 10, 11 );
$a_number = double_this ( $a_number );
print "$a_number $factor\n";

sub double_this {
    my ( $a_number ) = @_;
    my $factor = 2.0;
    return $factor * $a_number;
}

This'll print "20, 11", as expected.  The $factor in the subroutine is
a different variable, limited to the sub's scope, and changing it
doesn't affect the $factor in the main body.

But, if you're not using "my" and strict, you'll get trouble when you
reassign $factor:

( $a_number, $factor ) = ( 10, 11 );
$a_number = double_this ( $a_number );
print "$a_number $factor\n";

sub double_this {
    ( $a_number ) = @_;
    $factor = 2.0;
    return $factor * $a_number;
}

This'll print "20 2", almost certainly not what you wanted.

Now, this is certainly a cooked-up example, but it's suprisingly easy
to run into it in real life.

--Kester


More information about the Oakland mailing list