Print substitution ?

B

Bob

I am trying to read in the contents of a file (which contains psuedo
variables) and then print the file's contents and have variable
substitution occur.

Example:

[file contains this text: "Your name is $name"]

open (HEADER, "< ../header.htm")
my @headerLines = <HEADER>;
my $name = "Freddy";
print_html("@headerLines");

When I do this, I get the contents of the file, but the variable does
not get substituted. So the output looks like this:

Your name is $name

Suggestions ? This is actually part of a much larger file read with
many more variables and I could really use substitution.

Thanks,
 
M

michaelpgee

Try something more like:

my $name = 'Freddy';
open(my $header, '<', '../header.htm') or die "Can't read
'../header.htm': $!\n";
for (<$header>) {
s/(\$\w+)/$1/eg;
print_html($_);
}
close($header);
 
P

Paul Lalli

Bob said:
I am trying to read in the contents of a file (which contains psuedo
variables) and then print the file's contents and have variable
substitution occur.

Your Question is Asked Frequently
perldoc -q expand
How can I expand variables in text strings?

Paul Lalli
 
S

Sherm Pendley

Bob said:
I am trying to read in the contents of a file (which contains psuedo
variables) and then print the file's contents and have variable
substitution occur.

Search CPAN for the word "template" - this is very well-explored territory,
so there's little need to reinvent that particular wheel.

sherm--
 
J

John Bokma

Bob said:
I am trying to read in the contents of a file (which contains psuedo
variables) and then print the file's contents and have variable
substitution occur.

Example:

[file contains this text: "Your name is $name"]

open (HEADER, "< ../header.htm")
my @headerLines = <HEADER>;
my $name = "Freddy";
print_html("@headerLines");

When I do this, I get the contents of the file, but the variable does
not get substituted. So the output looks like this:

Your name is $name

Suggestions ? This is actually part of a much larger file read with
many more variables and I could really use substitution.

my %vars = (

name => "Freddy",
:
:
);

while ( my $line = <HEADER> )

$line =~ s{\$(\w+)}{

defined $vars{ $1 } ? $vars{ $1 } : 'ERROR'
}ge;

print $line;
}

(untested, use at your own risk, etc.)

But as Sherm already explained: there are many template solutions @
CPAN.

Some tips though:

check your open
don't use camelCase (it's Perl, not Java)
"@headerLines" probably doesn't do what you want.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,187
Latest member
RosaDemko

Latest Threads

Top