[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] reading variables from files



> What I want to be able to do is have a text file that contains:
> 
> "I'm going to print out the var $myVar\n"
> 
> Read it into my script, and when I print it from the script have it subsitute
> the variable.
> 
> 1) Can I do what I want to do? The reason I want to do this is I'm creating a
> form where the people using it need to edit the text, but variables I'm
> pulling from a database are sprinkled throughout the text. I don't want them
> to have to edit the script.
> 
> 2) Is there an easier way to read a glob of text into a variable?
> 

If you want the variables interpreted with their variables at the time
of the print statement, you need perl to interpret the text just
before the print statement. I guess that means eval "".

$Whattoprint = eval join('',@myData);

print $Whattoprint;

(The join() operator may be the answer to your question of how else to
put a glob of text info a variable.)


Maybe you could define your own tokens and substitute them in while
you read the text.

template file:
I'm going to print out %%myVar%%

code:
%replacementtext = ('myVar', 'Hi there', 
                    'replace_this', 'something else');

open(MYINPUT,$myFile) || die "Can't open $myFile: $!\n";
while(<MYINPUT>) {
  s/%%(\w+)%%/$replacementtext{$1}/g;
  print;
}

or with a little bit of error checking
while(<MYINPUT>) {
  while(s/%%(\w+)%%/$replacementtext{$1}/) {
    warn "What in the world is  %%$1%%\n" unless exists $replacementtext{$1};
  }
  print;
}