variable interpolation and file read

J

jkatz

Can I force variable interpolation on a file read?
I'd like the two print statements below to produce the same
results.....
(where the file myinputfile just contains the exact characters in $line
below--
without the quotes of course. )


#!/usr/bin/perl -w


$myvalue="girl";
$line= "It's a $myvalue ";
print $line."\n";

open (INPUT, "<myinputfile");
$line=<INPUT>;
print $line."\n";

Alternatively, how could I use a s/// to make the substitution?
(I want the substitution to work automatically for ANY variable I might
have
set earlier in the perl file.)

Thanks in advance for your help!

LCK
 
J

jkatz

In fact efficency isn't a big issue here--the input files aren't very
big. However the contents of $line can't be known by the perl script
beforehand, only the names and values of the variables.
I think however that what you suggests implies that I should read
$line,
split on either side of $myvalue and then eval
$myvalue. Am I understanding you correctly?

LCK
 
S

Sherm Pendley

In fact efficency isn't a big issue here--the input files aren't very
big. However the contents of $line can't be known by the perl script
beforehand, only the names and values of the variables.

Reading between the lines a bit, it sounds like what you're looking for is
a "template" library. These work sort of like the old "mad-lib" games. You
create a template with placeholders in it, and then the template library
reads that and fills in the proper values.

There are many such libraries available in CPAN- search for "template" at
<http://search.cpan.org>.

My own favorite is the venerable Text::Template, although that's largely a
matter of intertia on my part. I tried it out early on (I think it was the
first such module on CPAN), and it's never pissed me off enough that I've
felt the need to look at alternatives.
I think however that what you suggests implies that I should read
$line, split on either side of $myvalue and then eval
$myvalue. Am I understanding you correctly?

A word of advice: Before you consider taking PG's advice on *anything*, you
might want to review her posting history here.

sherm--
 
B

Brian McCauley

Can I force variable interpolation on a file read?

No.

See FAQ: "How can I expand variables in text strings?"

However the FAQ answer is incomplete so see also numerous[1] previous
threads on the subject by seaching for the phrase "How can I expand
variables in text strings?"

[1] ~2/month for the last few years.
 

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

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top