Reputation: 5763
I'm trying to read a FORTRAN program using Perl, and remove an INCLUDE
command and replace it with a USE
.
This is working great, except when printing out the contents of the hash storing the existing USE
statements, I get an extra entry.
my @lines = ( );
my %uses = { };
foreach $f1line (<>) {
$f1line =~ s/\r[\n]*//g;
if ($f1line =~ /^\s*INCLUDE 'FILE1.CMN'/ ||
$f1line =~ /^\s*INCLUDE 'FILE2.CMN'/ ||
$f1line =~ /^\s*INCLUDE 'FILE3.CMN'/) {
$f1line = " USE My_Mod";
}
if ($f1line =~ /^\s*USE /) {
$uses{$f1line} = 1;
}
push @lines, $f1line . $/;
}
$found = 0;
foreach $line (@lines) {
if ($found == 0 && $line =~ /^\s*USE /) {
foreach my $x (sort(keys(%uses))) {
print $x . $/; # (1)
}
$found = 1;
} elsif ($found == 1 && $line =~ /^\s*USE /) {
next;
} else {
print $line;
}
}
The output is this:
C Include parameters here
USE My_Mod
USE MyOther_Mod
USE EvenAnother_Mod
HASH(0x7f9dc3805ce8)
Where is the HASH(0x...)
reference coming from? The only place I'm printing the contents of the hash is on line (1)
. It almost looks like iterating over the keys of the hash is somehow including the hash itself.
How can I get rid of this?
Upvotes: 1
Views: 252
Reputation: 433
You are not really having a big problem, the big deal here is that you are not able to see the errors you are doing.
That's why you should always strict and warnings
In your code you start with:
my %uses = { };
When it should be:
my %uses = ();
or
my %uses; #it's fine also
And then it will works.
By using {}
in a "hash" context you could create a hashref which is not the case.
A reference to an anonymous hash can be created using curly brackets:
$hashref = { 'Adam' => 'Eve', 'Clyde' => 'Bonnie', };
Also is a good practice declare your variables in foreach
loop like:
foreach my $line (@lines) {
And in the rest of your code.
Upvotes: 6