in reply to Changing a single quoted string into an interpolated string

One way is eval:

eval qq{printf("$opt_F", 'foo', 'bar')};

But evaling something that is given on the commandline isn't probably a good idea!
Use taint mode and untaint it first!

Replies are listed 'Best First'.
Re: Re: Changing a single quoted string into an interpolated string
by Coyote (Deacon) on Aug 28, 2001 at 00:42 UTC
    I posted my original question a bit too quickly. The qq operator does exactly what I want it to do without using an eval block. Is there any reason to use taint mode if the code isn't going to be evaluated? Also, I am checking the format of the argument for validity in my production code. I just cut it out to simplify the example code.

    Update:

    I completely fooled myself with a bug in my code. qq does not work with out doing an eval. busunsl's solution works as expected, but isn't optimal because of the taint issue and the fact that I'm actually using sprintf in my production to build a hash rather than using printf to dump the results to STDOUT. After playing with it a while, I came up with a solution that uses a translation table and a regex to convert the single quoted string to a double quoted string. Some sample code follows:

    #!perl -w use strict; use Getopt::Std; use vars qw($opt_F); sub q2qq{ my $i = shift; print $i; my %t = map { $_, eval "qq(\\$_)" } split // , 'befnrt'; $i=~s/\\([befnrt])/$t{$1}/go; return $i; } getopts('F:'); print "Before: \n"; printf($opt_F, 'foo', 'bar'); $opt_F = q2qq($opt_F); print "\nAfter: \n\n"; printf ($opt_F, 'foo','bar');

    The result of running sample.pl -F %s:\t%s\n yields:

    Before: foo:\tbar\n%s:\t%s\n After: foo: bar
    ----
    Coyote