Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warn when using a variable on the same statement it is locally masked #17796

Open
caribpa opened this issue May 21, 2020 · 0 comments
Open

Warn when using a variable on the same statement it is locally masked #17796

caribpa opened this issue May 21, 2020 · 0 comments

Comments

@caribpa
Copy link

caribpa commented May 21, 2020

Two days ago I spent quite some time debugging this code:

# a lot of code

my $num = 0;

# more code

sub test {
    # complex function

    return (my $num = shift) ? $num : 0;
}

# ...

say test 4;  # 0

# ...

When I found the bug I initially thought that the issue was related to the ternary operator. But after creating an issue (#17795) I learned that you cannot use variables on the same expression they are declared, excerpt shared by @Grinnz from the documentation:

The declared variable is not introduced (is not visible) until after the current statement.

Currently these will generate a compilation error under strict (Global symbol "$n" requires explicit package name) and a warning under warnings (Name "main::n" used only once: possible typo):

(my $n = shift) ? $n : 0; 

if ((my $n) || !!$n) { $n } else { 0 }

But this will only generate a compilation error under strict (nothing with warnings):

((my $n) || !!$n) ? $n : 0;  # Perl thinks it's fine when not using strict

Anyways, if you do something like the code I showed on the first example, Perl won't warn you nor generate a compilation error and will probably do what you did not mean to do:

my $num = 0;
{
    local @_ = 10;
    (my $num = shift) ? $num : 0;                         # 0
}
{
    local @_ = 10;
    if ((my $num = shift) && !!$num){ $num } else { 0 };  # 0
}

and I can say first hand that finding this bug is something really time-consuming with no pragma nor Deparse to help you.

I'd like to see a warning here saying that you are using a variable on the same statement you are lexically masking it.

Though I see that this warning would also appear on the likely more common case:

local @_ = @_;
local $_ = $_;
# and so
@caribpa caribpa changed the title [feature] Warn when using a variable on the same statement it is locally masked Warn when using a variable on the same statement it is locally masked May 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant