Although using
local will solve your problem, I'd stay away from it. While it does "fix" that one problem, you still read the stylesheet file each time you encounter a tag to substitute. Since you open the stylesheet file each time, reading exactly the same data, it would make a lot more sense to read it once, like
jdporter suggests.
Here's an example of my take:
use strict;
use warnings;
my $stylesheet_file = "stylesheet.txt";
sub read_stylesheet
{
open(STYLESHEET, "<", $stylesheet_file)
|| die "Cannot read stylesheet_file\n";
my (%tag, $header);
while (<STYLESHEET>)
{
if (/^HEADER\s+(\d+):/)
{
$header = $1;
}
elsif (/^nm\s+:\s+(\w+)/
{
# Make a note of what header this tag
# appeared in.
$tag{$1} = $header;
}
}
close(STYLESHEET);
return \%tag; # Returns a reference to the hash
}
# ... (Main routine)
my $input_file = "taggedfile.txt";
my ($output_file) = @ARGV;
my $tag = read_stylesheet();
open(FILE, "<", $input_file)
|| die "Could not read $input_file\n";
open(OUT, ">", $output_file)
|| die "Could not write $output_file\n";
while (<FILE>)
{
# Perform substitutions
s/^\{(\w+)\}/\{$1:$tag->{$1}\}/g;
# Write line ($_) to OUT
print OUT;
}
close(FILE);
close(OUT);
This variation has a routine which reads in the stylesheet and returns a hash reference to the data that was read. Theoretically, then, you can read in more than one stylesheet and choose which one you look up from, something that a global variable doesn't really permit.
You shouldn't have to localise $_ if you're careful about what's going on. Having nested file reads is one way to cause trouble, which is what you had there.
If you're not sure where $_ has been, the safe thing to do is used a named variable, such as this:
while (my $line = <FILE>)
{
# ... Use $line where you would normally use $_
}
I'd really suggest steering away from using
local declared variables.