I know you can do this, I just can't find it.
How do you call a sub within a qq{} construct
qq{The common term for H2O is chem("H2O").}
Thank you
(As soon is this post is complete... I'll find it)
Its a little like the tail wagging the dog.
-> "The common term for %s is %s."
This doesen't change, so a sprintf is all you need.
Sometimes its a problem if you need to print the same thing
at different places in the program.
Taking your theme of qq(), you can split a message format string
from the data and consistently call a message formatter that puts
it all together.
This is just for example purposes. Should you need a full
blown formatter, there are probably dozens of safe ones on
Cpan.
-sln
---------------
use strict;
use warnings;
my $common_msg = qq{"The common term for '%s' is '%s'."};
my $chem_msg = qq{"'%s' is the common term for '%s'."};
my %chemterms = (
'H20' => 'water',
'C02' => 'carbon dioxide',
'02' => 'oxygen',
'NaCL' => 'sodium chloride',
);
my %commonterms = reverse %chemterms;
##
for (sort keys %chemterms) {
print getMsg($common_msg, $_, chem($_)), "\n";
}
for (sort keys %commonterms) {
print getMsg($chem_msg, '\u'.$_, chem(-$_)), "\n";
}
exit 0;
##
sub chem {
my ($key) = @_;
return $commonterms{$key} || 'undefined' if $key =~ s/^-//;
return $chemterms{$key} || 'undefined'
}
sub getMsg {
my ($msg, @data) = @_;
my $retval = '';
my $evstr = "\$retval = sprintf ($msg, ". "@{[map {qq(\"$_\",)} @data]}" .");";
eval $evstr;
return $retval;
}
__END__
The common term for '02' is 'oxygen'.
The common term for 'C02' is 'carbon dioxide'.
The common term for 'H20' is 'water'.
The common term for 'NaCL' is 'sodium chloride'.
'Carbon dioxide' is the common term for 'C02'.
'Oxygen' is the common term for '02'.
'Sodium chloride' is the common term for 'NaCL'.
'Water' is the common term for 'H20'.