Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Uer Perl Variable in txt file

by vinaybond (Novice)
on Aug 06, 2012 at 13:47 UTC ( #985721=perlquestion: print w/ replies, xml ) Need Help??
vinaybond has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have a file which has contents like this.
file.txt
This is $name

my.pl $name = "Test"; open(FH,"file.txt"); while(<FH>){ print "$_"; }
Here is output I am getting:
This is $name

I want output like this
This is Test

I can achieve this using regexp ($_=~s/\$name/$name/;) but there are multiple variable in the file and I have to write N regexp line for N number or variable.

Is there another simple way.

-Vinay

Comment on Uer Perl Variable in txt file
Download Code
Re: Uer Perl Variable in file
by choroba (Abbot) on Aug 06, 2012 at 13:57 UTC
    Using a hash instead of variables is safer (no eval needed). Something like this:
    #!/usr/bin/perl use warnings; use strict; my %replace = (name => 'Joe', fun => 'a game'); while (<DATA>) { for my $key (keys %replace) { s/\$$key/$replace{$key}/g; } print; } __DATA__ Hullo $name, are you ready for $fun?
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
        my $search_for = join '|', map quotemeta, keys %replace; ... s/\$($search_for)/$replace{$1}/g;
        Additionally:
        when doing things like this and you have two hash keys "foo" and "foobar", either use \b in the regex if possible, or sort the hash keys for length before joining. otherwise $foobar could be replaced with the value of $replace{foo}.
        s/\$($search_for)\b/$replace{$1}/g;
Re: Uer Perl Variable in file
by Anonymous Monk on Aug 06, 2012 at 14:24 UTC

    I don't feel that I understand what you are getting, based on the snippet of source code that I see ... but here is one important thing to keep in mind: the difference between single and double quotes.

    A string such as 'This is $name' will be output literally as it appears, whereas a string in double quotes such as "This is $name" will have the variable-name interpolated.   That is, if $name is Fred, you get:   This is Fred in the second case but not the first.

      I have a file which has contents like this

      ______file.txt_______
      I am $name
      I am from $city
      I live $food
      I got $car


      Using perl code I am reading line one by one from file.txt. When I print line using $_ it does not replace variable in text file with variable values in .pl file but it prints the line as it is.
      -Vinay

      Because this is external data, the interpreter will not interpolate variables

      --linuxkid


      imrunningoutofideas.co.cc
Re: Uer Perl Variable in txt file
by rovf (Priest) on Aug 06, 2012 at 14:52 UTC
    Although choroba already warned against using eval - and he is certainly right with it -, you can consider an eval-solution, if you understand the risks (and, in particular, if you have control over what goes into your file).

    In this case, you could do:

    use strict; use warnings; while(my $line=<FH>) { print(eval "qq($line)"); }
    This solution is much simpler than doing a substitution manually, but never forget: Whoever creates file.txt, can get *any* code being executed by your program; it requires that every variable referenced in the file, exists in the scope of evaluation (and will be replaced); and finally, that, if file.txt contains parentheses, that they are balanced.

    -- 
    Ronald Fischer <ynnor@mm.st>
      eval stinks in such an application, as of course well you know.   It would only "work perfectly" in a perfect situation, and who knows what it would do at all other times.   Unacceptable.
        eval stinks in such an application
        Admittedly, it at least smells funny. However, I personally don't like to tell people in those situations that it is unacceptable in an absolute sense, because we don't know what's their application is, and what risk they are willing to take (in exchange for easier programming). That's why I outlined every risk I was aware off. With other words: Instead of saying: "Don't shoot yourself in the head", I prefer saying: "You can shoot yourself in the head, but be aware that there will be a hole afterwards". ;-)


        Having said this, I must admit that I would use such an eval solution for work I only use myself (not paid work for the customer), knowing well that I can't blame anyone but myself if I get bitten....
        -- 
        Ronald Fischer <ynnor@mm.st>
      Thank you very much. It solved my problem. I can use eval without worry as i am the one who is creating the file. -Vinay

        Thank you very much. It solved my problem. I can use eval without worry as i am the one who is creating the file. -Vinay

        And you never make mistakes? :)

        I would worry about making mistakes, maybe not today, but a week from now, so I would avoid string eval unless this was a single-use-program, only to be used once

        Otherwise I would use String::Interpolate or String::Interpolate::RE or another similar abstraction instead

Re: Uer Perl Variable in txt file
by linuxkid (Sexton) on Aug 06, 2012 at 15:41 UTC

    Have you considered Template, the template toolkit?

    --linuxkid


    imrunningoutofideas.co.cc

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://985721]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (10)
As of 2014-12-27 18:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls