Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

<paragraph> I asked a while back about expanding variables in text strings and was refered to How can I expand variables in text strings? which answered the question "How can I expand variables in text strings?". It looks like the code there would work for most cases.

However, I still haven't gotten this to work on the following user input string

TESTDATA_BETA$CurrentVal[1]_DEFL$CurrentVal[2].$CurrentVal[0]
I've tried several things including
$OutputFileFormat =~ s/\$(\w+\])/${$1}/g
with no luck.

This should probably be obvious, but I'm just not getting it. Thanks for the help so far! This is the last bit of code I need to get working to complete my program. </paragraph>

Edit 2001-03-14 by tye

Replies are listed 'Best First'.
Re: Another question about expanding variables in text strings
by dvergin (Monsignor) on Mar 15, 2001 at 03:28 UTC
    First, your regex wasn't matching. For example, \w does not match '[' as would be necessary for your expression to succeed. And \w does match '_' which complicates things since you have '_' as a char right after the variable you want to interpolate.

    Second, if you are using use strict; (recommended) and variables declared with 'my', you need to use the approach for lexicals given on the page you mention:

    my @Val = qw(aaa bbb ccc); my $str = 'TESTDATA_BETA$Val[1]_DEFL$Val[2].$Val[0]'; if ($str =~ s/(\$[^]]+\])/$1/gee) { print "$str\n"; }
    This assumes all the interpolated values are array values. If that is not the case, a different approach will be needed in the first half of the regex. Perhaps something like: s/(\$[a-zA-Z0-9[\]]+)/$1/gee which also works with the example data you gave.

      Starting from something I rolling in (tye)Re: Trying to understand some body's old code.: s/(\$[\w\[\]{}']+)/'"'.$1.'"'/gee; I thought that wouldn't work for this case and went about making elaborate changes... But then I realized that the original should work just fine (and even tested it). (:

              - tye (but my friends call me "Tye")
      Thanks for the help. I'm not sure I totally understand the pattern matching string, but I'll do some digging in the Programming Perl book. The most important thing is it works :)
Re: Another question about expanding variables in text strings
by Hot Pastrami (Monk) on Mar 15, 2001 at 02:40 UTC
    Anything wrong with join()ing? It's not as confusing to read, and just as fast:
    join '', "TESTDATA_BETA", $CurrentVal[1], "_DEFL", $CurrentVal[2], "." +, $CurrentVal[0];

    Hot Pastrami
Re: Another question about expanding variables in text strings
by telesto (Novice) on Mar 15, 2001 at 05:17 UTC
    You could try to not be greedy:

    s/\$(.*?\])/${$1}/g

    --telesto