The August
The August

Reputation: 469

Perl subroutine local global issue

For this tiny code, it always prints the values of @x in the Global block of code. How to issue an warning if I accidentally don't initialize a variable inside a subroutine without 'my @x'. I wan't a local variable in the subroutine as @x.

use strict;
use warnings;
my @x=qw/1 2 3/;

&mysub();

sub mysub{

    print "@x";
}

Upvotes: 1

Views: 127

Answers (2)

ikegami
ikegami

Reputation: 385655

  1. Organize your code better.

    use strict;
    use warnings;
    
    sub mysub{
        print "@x";
    }
    
    {
        my @x=qw/1 2 3/;
        mysub();
    }
    

    By properly localizing variables, there's no change of accidentally referring to the wrong one.

  2. Don't use such meaningless variable names.

    There's little chance of accessing @frobs_by_name by accident.

Upvotes: 0

simbabque
simbabque

Reputation: 54323

With regular Perl you cannot do that. The solution is not to reuse the same variable names in smaller scopes.


If you want to enforce this programmatically, you can use Perl::Critic. The policy Perl::Critic::Policy::Variables::ProhibitReusedNames tells you if you have reused variable names that are already defined in an outer scope.

Upvotes: 6

Related Questions