in reply to keeping $$this defined locally

Could you explain why you want to do that? I didnt have time to ask you on the chatterbox earlier...

Replies are listed 'Best First'.
RE: RE: keeping $$this defined locally
by Specimen (Acolyte) on Oct 04, 2000 at 19:19 UTC
    A program reads in a template (not mine) which has fields defined 
    
    first=one
    second=two
    
    then it reads in another file with stuff like
    
    "adding $first and $second we get third"
    
    i loop through the variables from the template, and pretty
    much do this for each one (assume $newstring points at the
    string above):
    
    {
    ($variable, $value) = split("=", $linefromtemplate);
    $$variable = $value;
    $newstring = eval("return \"$newstring\");
    }
    
    Not beautiful I agree...but seemed a quick way of doing what
    I want - only I dont want the newly associated variables
    to be applicable outside of the scope of the block they 
    are declared in.
    
    (And strict complains about it too)
    
    Thanks
    
    Specimen
      That template looks like it was written for a shell.

      Anyways I would use a hash for the keys and regular expression substitution. So the first file would be read like:

      my @entry = split(/=/, $line, 2); $val{$entry[0]} = $entry[1];
      and then substitute them in with:
      s/\$(\w+)/exists($val{$1})?$val{$1}:die "Undefined '$1' in entry '$new +string' (line $.)"/eg;
      Now strict should be happy, and things are easy to scope. Plus I stuck a minimal error check in.

      Oh, and strangle the person who wrote the stupid template willya?

        Yup - combining a few messy sh scripts into a perl one.

        Thanks. I'll try doing that - i was actually going to do that initially - thought i'd take the easy route out and let eval do all my work for me though.

        Specimen
    • You probably should use a high-quality templating CPAN module, such as Template or Text::Template
    • If you insist on homegrowing your tmeplate module, the chief means of isolating variables within Perl are packages or hashes.
      1. For hashes, here's a snippet:
        { my %template_var; my ($key,$val) = split '=', $linefromtemplate; $template_var{$key} = $val; }
      2. And for packages, here's another:
        { package template_var; my ($key,$val) = split '=', $linefromtemplate; no strict 'refs'; $$key = $val;# left out symbolic dereference use strict 'refs'; }

        I woulda caught my error if we could preview replies to other posts...Why dont we enable that?