Discipulus has asked for the wisdom of the Perl Monks concerning the following question:
I have found two approach at this problem: Re: Dreaming of Post Interpolation that propose an quoting-evaluating workaround (not suitable for thinks like @sec ? @sec : 'empty')#!perl use strict; use warnings; $|++; my ($comp,$first,@sec); $comp = "descr is ".(defined $first ? q{$first} : 'null').' and list i +s '.( @sec ? q{join ' ', @sec} : 'empty'); print "Oringinal:$comp\n"; &modify_first('UNO'); &modify_second (1);&modify_second (2); &modify_first ('DUE'); &reset_second; sub modify_first{$first = shift; print "$comp\n";} sub modify_second {push @sec, shift; print "$comp\n";} sub reset_second {@sec=qw(); print "$comp\n";} __OUTPUT__ Oringinal:descr is null and list is empty descr is null and list is empty descr is null and list is empty descr is null and list is empty descr is null and list is empty descr is null and list is empty
my $text = q{ Dear $person, I know that this text is $adjective. But I wish it could be... }; my $person = 'Mom'; my $adjective = 'not interpolated'; print eval "qq{$text}"; __OUTPUT__ Dear Mom, I know that this text is not interpolated. But I wish it could be...
The Perl faq propose:my $n = sub {1}; my $m = sub {&$n*2}; my $o = sub {&$m*2}; my $s = sub {&$n." ".&$m." ".&$o."\n"}; print &$s; $n = sub {2}; print &$s; __OUTPUT__ 1 2 4 2 4 8
How can I expand variables in text strings? Let's assume that you have a string that contains placeholder vari +ables. $text = 'this has a $foo in it and a $bar'; You can use a substitution with a double evaluation. The first /e +turns $1 into $foo, and the second /e turns $foo into its value. You may + want to wrap this in an "eval": if you try to get the value of an undec +lared variable while running under "use strict", you get a fatal error. eval { $text =~ s/(\$\w+)/$1/eeg }; die if $@; It's probably better in the general case to treat those variables +as entries in some special hash. For example: %user_defs = ( foo => 23, bar => 19, ); $text =~ s/\$(\w+)/$user_defs{$1}/g;
my $color = "red"; my $fruit = "apple"; my $name = "chromatic"; my $string = 'Hi, my name is $name. Please hand me a $color $fruit.'; print ">>$string<<\n"; # demonstrate what we have my $s2; eval "\$s2 = qq/$string/"; # the real magic print "->$s2<-\n"; # demonstrate the result __OUTPUT__ >>Hi, my name is $name. Please hand me a $color $fruit.<< ->Hi, my name is chromatic. Please hand me a red apple.<-
|
|---|