1

As in the following example with $DimensionSwitch, I like to reuse the names of variables. I know $DimensionSwitch is lexically scoped, so it doesn't appear to cause any problems, but (1) might it cause problems somewhere that I don't know about and therefore (2) is it poor practice to reuse variable names in Perl?

my $DimensionSwitch = checkDimensions(\@coefficients,\@predictors);
sub checkDimensions{
    my @a1 = @{$_[0]};
    my @a2 = @{$_[1]};
    my $Size1 = @a1;
    my $Size2 = @a2;
    my $DimensionSwitch;
    if ($Size1 == $Size2){
        $DimensionSwitch = 1;
    }else{
        $DimensionSwitch = 0;
    }
    return $DimensionSwitch;
}
1
  • 3
    If it's scoped then it won't cause problems elsewhere, but it will be confusing, if not for you, then for someone else reading your code. Best avoided! Commented Jul 22, 2014 at 7:18

3 Answers 3

2
  1. It shouldn't
  2. It's not bad per se. It is bad if it makes more difficult to read code
  3. and the code...

    my $DimensionSwitch = int(@coefficients == @predictors);
    
Sign up to request clarification or add additional context in comments.

2 Comments

Neat, int to force 1/0 instead of 1/''.
It is there to play safe. I'm pretty sure the variable is checked on being truthy, not exactly 1 or 0. But I don't know the rest of author's code.
1

It's really usefull use pragma 'use strict' in Perl. This pragma is not the cure for all but you could use also 'use warnings' and perl it self will advice you of many nasty things :)

http://perldoc.perl.org/strict.html

Comments

1

Reusing variable names within a lexical scope isn't forbidden but can be confusing and create subtle maintenance headaches.

You can use Perl::Critic::Policy::Variables::ProhibitReusedNames as an analysis tool.

A nice web interface allows you to upload your code for analysis at varying degrees of brutality here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.