in reply to Re^2: Interpolating strings within strings
in thread Interpolating strings within strings
If your variables are in a hash, the following doesn't compile the string at runtime. It's safer and possibly faster. I've even added an esacpe sequence (${$}) in case you need to use $!
%vars = ( FTPPath => '/my/ftp/path', TransferMode => 'ASCII', ); s/(\$(\w+|{(\$|\w+)}))/ my $var = defined($3) ? $3 : $2; $var eq '$' ? '$' : (defined($vars{$var}) ? $vars{$var} : $1); /eg;
Test code:
%vars = ( FTPPath => '/my/ftp/path', TransferMode => 'ASCII', ); foreach ( 'cd $FTPPath', 'type ${TransferMode}', '${$}escaped!', ) { my $command = $_; $command =~ s/(\$(\w+|{(\$|\w+)}))/ my $var = defined($3) ? $3 : $2; $var eq '$' ? '$' : (defined($vars{$var}) ? $vars{$var} : $1); /eg; print("$command\n"); } __END__ ourput ====== cd /my/ftp/path type ASCII $escaped!
|
|---|