Perl 'My' Variable [$] makes earlier declaration in same statement

3.9k Views Asked by At

So I have a few sub rutines for opening a file:

828 sub open_for_r {
829     my $FH = shift;
830     my $filename = shift;
831 
832     open($FH, "< $filename") || die "cannot open $filename: $!";
833 }
834 
835 sub open_for_w {
836     my $FH = shift;
837     my $filename = shift;
838 
839     open($FH, "> $filename") || die "cannot open $filename: $!";
840     # open($FH, ">> $filename") || die "cannot open $filename: $!";
841 }
842 
843 sub open_for_rw {
844     my $FH = shift;
845     my $filename = shift;
846 
847     open($FH, "+< $filename") || die "cannot open $filename: $!";
848     # open($FH, ">> $filename") || die "cannot open $filename: $!";
849 
850 }
851 
852 sub read_file {
853 
854     my $FH = shift;
855     my $filename = shift;
856     my $contents = "";
857     my $var = "";
858 
859     #To read from that file
860     while (defined($var = <$FH>)) {
861         # chomp($var);
862         # print "$var\n";
863     $contents .= $var;
864     }
865     return $contents;
866 }

Now I am getting a warning:

"my" variable $FH masks earlier declaration in same scope at ittp_to_scn.pl line 836.

"my" variable $filename masks earlier declaration in same scope at ittp_to_scn.pl line 837.

"my" variable $FH masks earlier declaration in same scope at ittp_to_scn.pl line 844.

"my" variable $filename masks earlier declaration in same scope at ittp_to_scn.pl line 845.

Although nowhere else in my code do I have the $FH or $filename declared. I don't understand why it is saying that there is an earlier declaration? Aren't I allowed to use the same variable names in different sub routines? Or is this not allowed in Perl?

2

There are 2 best solutions below

0
On

Turned on use strict and fixed some warnings. So there was no issue, just other issues caused these warnings.

0
On

Well, I got this warning today and I DID have

use strict;
use warnings;

enabled.

I went through the code looking for missing ; and extraneous {s and }s and found a superfluous } a few lines above where the issue was at the end of a statement (but before the semicolon).