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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.