in reply to super-simple regex-based template eval --- handling undefined substitutions

Does the following help?

use Modern::Perl; use warnings FATAL => qw{ uninitialized }; my $abc = "ABC"; my $def = "DEF"; ## no $ghi is defined. my $jkl = 0; my $funnystring = 'hello $abc and $def and $ghi and $jkl'; $funnystring =~ s/(\$\w+)/defined eval $1 ? eval $1 : "unknown $1" /ge +; print $funnystring;

Output:

hello ABC and DEF and unknown $ghi and 0

Update: Changed from single to double quotes (i.e., "unknown $1") in the ternary operator to show unknown $ghi in output instead of unknown $1.

Replies are listed 'Best First'.
Re^2: super-simple regex-based template eval --- handling undefined substitutions
by iaw4 (Monk) on Sep 15, 2012 at 22:40 UTC
    yes, it does help. thanks. of course, it would be nicer if unknown $1 were to become 'unknown $ghi'. but it's a great one-liner, nonetheless.

      Using double quotes in the ternary operator will achieve this. Have updated the code to do this...