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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.