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

I created an HTML page I need to get my script to work with. I decided the easiest way would be to drop $var placeholders in my code where I want each of the "active content" to load into. I have $galleryname, $gallerypictures, etc as placeholders.

Now when I get($page) via LWP::Simple, how do I then s/$var/ with the results of a subroutine? Each placeholder has their own subroutine to determine what will be printed in that section.

$page =~ s/\$galleryname/&galleryname/;

Replies are listed 'Best First'.
Re: Regex to replace $vars with subroutine
by friedo (Prior) on Jun 06, 2008 at 19:53 UTC
    The proper way to do this is with one of the many templating modules that exist on CPAN, such as HTML::Template. But if you truly want to roll your own, you can use the /e option on your regex (see perlre) to make the replacement string executable code.
Re: Regex to replace $vars with subroutine
by Corion (Patriarch) on Jun 06, 2008 at 20:05 UTC

    All you're missing is the /e modifier, see perlre.

    $page =~ s/\$galleryname/galleryname()/ge
      Hi.
      Can you see why this isn't working as expected?
      use warnings; use strict; my $string = "this is a test \$placeholder"; $string =~ s/\$placeholder/test_sub()/e; print $string; sub test_sub { print "hello there"; }
      # prints "hello therethis is a test1

      I don't want the subroutine to print anything, just do everything it needs to do and print out all output back into the $string

        Change print to return, and it works.

        use warnings; use strict; my $string = "this is a test \$placeholder"; $string =~ s/\$placeholder/test_sub()/e; print $string; sub test_sub { return "hello there"; }

        If you really need to capture the output of what a sub prints, that's a whole other problem. I was doing something like that in Use of uninitialized value in open second time but not first., and there's more discussion with it about other ways to do it.

Re: Regex to replace $vars with subroutine
by kyle (Abbot) on Jun 06, 2008 at 21:51 UTC
Re: Regex to replace $vars with subroutine
by Narveson (Chaplain) on Jun 06, 2008 at 19:58 UTC

    Update: Put $page through two passes of string interpolation.

    $galleryname = galleryname(); $page = eval "qq{$page}";

    It struck me right away that your $var placeholders are just begging to be interpolated.

    If gallery() returns 'the Rijksmuseum' and $page is 'Welcome to $gallery!', then eval will see qq{Welcome to $gallery} and $page will get 'Welcome to the Rijksmuseum!'