Sunday, July 17, 2022

[FIXED] How to re-declare a variable in the same scope in perl?

Issue

Is there a way to re-declare a variable in the same scope using the my keyword in perl? When I run the following script:

use warnings;
use strict;

my $var = 3;
print "$var\n";

undef $var;
my $var = 4;
print "$var\n";

I get the "desired" output, but there is also a warning "my" variable $var masks earlier declaration in same scope. Is there a way to re-declare the variable without getting the warning?

I'm not sure, but I think this is because my happens at compile-time and undef happens at run-time because the warning is being printed even before the first print statement. (I'm not even sure if perl actually compiles the thing before running it.)

Context: I want to be able to copy a chunk of code and paste it multiple times in the same file without having to edit-out all the my declarations. I guess this isn't the best way to do it, but any solution to the problem would be appreciated.


Solution

To avoid the warning, you can enclose the new variable declaration, and the code that uses it, inside curly braces ({...}) and create a new scope.

my $var = 3;
print "$var\n";

{    
    my $var = 4;
    print "$var\n";
}


Answered By - mob
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.