Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Uer Perl Variable in file

by choroba (Canon)
on Aug 06, 2012 at 13:57 UTC ( #985726=note: print w/ replies, xml ) Need Help??

in reply to Uer Perl Variable in txt file

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?
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Comment on Re: Uer Perl Variable in file
Download Code
Replies are listed 'Best First'.
Re^2: Uer Perl Variable in file
by moritz (Cardinal) on Aug 06, 2012 at 13:59 UTC
      my $search_for = join '|', map quotemeta, keys %replace; ... s/\$($search_for)/$replace{$1}/g;
      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}.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://985726]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (14)
As of 2015-07-28 09:39 GMT
Find Nodes?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...

    Results (254 votes), past polls