Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Replacing string with regexp without using modules

by pc88mxer (Vicar)
on Aug 05, 2008 at 22:51 UTC ( #702518=note: print w/replies, xml ) Need Help??

in reply to Replacing string with regexp without using modules

For your first question:
sub prog_replace_string { my ($replace_this, $with_this, $string) = @_; $string =~ s{\Q$replace_this\E}{$with_this}g; $string; }
For your second:
sub replace_vars { my ($string, $hash) = @_; $string =~ s{\$(\w+)}{$$hash{$1}}ge; $string; } my %vars = ( a => 1, b => 22, c => 333 ); print replace_vars('a: $a, b: $b, c: $c', \%vars);

Replies are listed 'Best First'.
Re^2: Replacing string with regexp without using modules
by cowgirl (Acolyte) on Aug 06, 2008 at 00:37 UTC
    Thanks for the great reply. It works well. However when I cut it down to this, it doesn't work:
    $string = '$a $b $c'; $hash{a} = "go"; $string =~ s{\$(\w+)}{$$hash{$1}}ge;
    Could it be the hash reference you use to the subroutine? \$hash ? Thanks.
      Could it be the hash reference ...?

      Yes, in pc88mxer's code, $hash is a hash reference, so it must be dereferenced. In your case, it's a normal hash.  So either don't dereference

      $hash{a} = "go"; $string =~ s{\$(\w+)}{$hash{$1}}ge;

      or create a reference

      $hash->{a} = "go"; $string =~ s{\$(\w+)}{$$hash{$1}}ge;

      or even use the normal arrow syntax in both the assignment $hash->{a} = ..., and when you access it $hash->{$1}:

      $hash->{a} = "go"; $string =~ s{\$(\w+)}{$hash->{$1}}ge;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://702518]
[stevieb]: I have learned that my daughter has significant brain injury, so that's affecting my decisions. Don't know who to reach out to. I just want to vent. I am honestly lost. It's something I can't code around.
[stevieb]: I am infuriated at the same time I am hopeless. It appears there are approaches to 'fix' things, but, you know..,

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2017-02-25 04:01 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (365 votes). Check out past polls.