http://www.perlmonks.org?node_id=156740


in reply to How do you replace variables in an external string?

Hello $cgi->param('name'), how are you today

For some reason, the CGI.pm author didn't realise that hashes are the most natural way of providing key/value-based information. Of course, the object orientation is a laudable approach in general, but CGI scripts often use the values in strings, and not having a hash is actually making the script less readable. It's one of my reasons for not liking CGI.pm.

Some (lshatzer and Kanji) have already given ways to use CGI.pm to put everything in a hash, so I'm not going to repeat them. I'll try to explain why what you tried didn't work.

You probably (hopefully) already know that variable interpolation works only with certain quoting operators, of which "" (double quotes, also known as qq//) is the most popular. The problem is that $cgi->param('name') is not a variable. It's a method call on $cgi. $cgi itself is a variable, and because there's no [ or { following the arrow, $cgi is used, and followed by a literal minus, greater than sign and the literal text param('name').

$cgi probably is a CGI object, and because of that, its string representation (Perl's one-way reference-to-string conversion) is CGI=HASH(0x...), with a memory address instead of dots, is used. Before the equal sign is the package name into which the reference was blessed, after it is a normal hash reference string representation. If you don't know what I'm talking about, just ignore the parts you don't get, and add "read perlref and perltoot" to your to-do list.

The following solutions would work:

my $name = $cgi->param('name'); print "Hello $name, how are you today?";
And so would non-interpolating string concatenation:
print 'Hello ' . $cgi->param('name') . ', how are you today?';
As would passing a list to print:
print 'Hello ', $cgi->param('name'), ', how are you today?';
And this trick also works (see also How do I expand function calls in a string?):
print "Hello ${\ $cgi->param('name') }, how are you today?";


Good luck!

U28geW91IGNhbiBhbGwgcm90MTMgY
W5kIHBhY2soKS4gQnV0IGRvIHlvdS
ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
geW91IHNlZSBpdD8gIC0tIEp1ZXJk