There must be a Perlish way to do this. . .
I have a situation where I want to load some text strings from a file for later printing, but the variables that are going to be inserted into the strings are not known until much later in the program. So what I think I want is to find a way to cause the string to re-interpolate the scalars.
Here's some sample code:
$message = "Hello $name\n";
#. . . other code that does unrelated stuff . . .
$name = "Larry Wall";
print $message;
What I'd like is for the message to print as "Hello Larry Wall", but what I get is "Hello".
Eval doesn't seem to work the way I would expect it to. (So I must be expecting incorrectly, too!)
I've tried this:
$message = "Hello $name\n";
#. . . other code that does unrelated stuff . . .
$name = "Larry Wall";
print eval $message;
I still just get "Hello" back. And then I got to thinking that maybe I got just the "Hello" because $name was already substituted, and by this time only "Hello" exists in the string (without the $name). So, I tried to declare $message with single quotes thusly:
$message = 'Hello $name\n';
#. . . other code that does unrelated stuff . . .
$name = "Larry Wall";
print eval $message;
And that didn't work either. I got nuthin.
I tried lots of other stuff that I'm embarassed to admit, and so I won't.
I'm running under the assumption that it is STILL true that "Perl makes easy things easy and hard things possible." I've a feeling that this comes under the first category, rather than the last. But either way, there must be a solution.
So how do I get Perl to re-interpolate the $message string when I need it to?
Thanks much, in advance.
--Mark
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.