Substitute variables when reading file 
Author Message
 Substitute variables when reading file

Quote:

> I have a Perl program which opens up a text file, and in this text file
> there are $variables.  How can I get Perl to map these
> $variables without explicity mapping each one.
> For example,

> Here's my Perl file;
> $name = "Neal";
> open (FILE, "file.txt");
> while (<FILE>) {
>   print "$_";
> }

> ----------file.txt-------
> Hi, my name is $name
> -------

> The output would be "Hi, my name is $name." BUT, I want it to be
> "Hi, my name is Neal."

The way I approach this problem is usually something like this.
1. Put the variables you want to substitute into a hash:
  %vars = (name => Neal,

           ...etc...
          );


$KEYWORD as you suggest is bad becuase it makes it basically
impossible to have a $ sign in your file for any other purpose (like
listing a dollar amount, for example.

3. Do the substitution like this:
my $filename = 'file.txt';
open(FILE, $filename) or die "Can't read $filename: $!\n";
while(<FILE>) {

  print;

Quote:
}

close(FILE);

A couple of other notes:
  1. Put the filename in a variable; you'll probably want to change it
sometime.
  2. Always check the return code from open().
  3. print with no arguments prints $_, and you shouldn't put double
quotes around a plain variable: it's superfluous.

HTH.

--Bill.

[posted and mailed]

--
William R Ward          Bay View Consulting   http://www.*-*-*.com/ ~hermit/


 PGP Key 0x2BD331E5; Public key at http://www.*-*-*.com/ ~hermit/pubkey.txt



Sat, 17 Jun 2000 03:00:00 GMT  
 
 [ 1 post ] 

 Relevant Pages 

1. Substitute variables when reading file

2. Substituting variables in a text file

3. Substituting $variable strings in a file

4. split and substitute, substitute, substitute

5. Newbie Q: variable replacement part of substitute

6. Retreiving a template, and substituting variables

7. substituting several variables at once.

8. Newbie - using variable for search or substitute option

9. Help needed: I cannot seem to get this variable to substitute in this pattern

10. Variables in Strings and Substituting a Path Name

11. Substituting variables in a string?

12. Reading line from file and assiging to variables

 

 
Powered by phpBB® Forum Software