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

My fellow monks, I sit before you with my head hung in shame. I have nearly been beaten. Below was intended to be a simple regular expression to replace $var or $var[0] or $var{hashname} or $var{'hashname'} or $var{"hashname"} with the correct value.

$HTMLLine =~ s/(\$[\w\[\]{}']+)/'"'.$1.'"'/gee;

The above line works fine on $var but won't work on anything else.

Any help would be great!

Replies are listed 'Best First'.
Re: expanding scalar content
by princepawn (Parson) on May 19, 2001 at 00:32 UTC
Re: expanding scalar content
by Sifmole (Chaplain) on May 19, 2001 at 01:08 UTC
    Well the following works for everything except $foo
    #!/usr/bin/perl -w use strict; my @tests; push (@tests, q($foo)); push (@tests, q($foo[0])); push (@tests, q($foo{bar})); push (@tests, q($foo{'bar'})); my $foo = 'scalarfoo'; my @foo = qw(arrayfoo); my %foo = ( 'bar' => 'hashfoo' ); foreach my $foo (@tests) { $foo =~ s/(\$[\w\[\]{}"']+)/qq($1)/gee; print $foo, "\n"; }
    I would also like to second the suggestion that you take a look at something like Text::Template or HTML::Template; Either of these will allow you to accomplish a similar effect and more. Of course alot depends on what your real goal is.
Re: expanding scalar content
by srawls (Friar) on May 19, 2001 at 01:12 UTC
    I'm not sure I understand what you want, this is my guess as to what you want (it's what happened when I ran the code):

    $HTMLLine has the literal $someVar, and you want to replace it with the value of the variable $someVar.

    If that is correct, just try this:

    $HTMLLine =~ s/(\$\S+)/$1/gee;
    It's not perfect, but it should do unless you have a lot of variables used like this:  ${varName}some other stuff in the string. But, it will work for things like this  $var this that and ${VAR} the @other

    The 15 year old, freshman programmer,
    Stephen Rawls
Re: expanding scalar content
by tadman (Prior) on May 19, 2001 at 03:02 UTC
    Just as a point of observation, the double-e means to double evaluate, correct? In the first pass, this would convert $1 to the equivalent string '$var' and then on the second pass, evaluate it to the value of $var. I didn't know you could do that.
      >>Just as a point of observation, the double-e means to double evaluate, correct? In the first pass, this would convert $1 to the equivalent string '$var' and then on the second pass, evaluate it to the value of $var. >>

      That is exactly right. You can put as many /e modifiers as you want, and it will be evaluated that many times.

      To solve the problem, you basically have two choices (well, I can think of two, there are probablly more), multiple /e modifiers or symbolic references. Personally, I think that the double-e approach is a bit cleaner than using symbolic references.

      The 15 year old, freshman programmer,
      Stephen Rawls