Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Multiline Regex replacement in Multiline file

by Grimy (Pilgrim)
on Sep 15, 2014 at 09:19 UTC ( [id://1100572]=note: print w/replies, xml ) Need Help??


in reply to Multiline Regex replacement in Multiline file

Howdy akamboj84,

In the replacement part of your regex, $dic{$matchkey} will always be undefined. $matchkey is the variable you defined above by joining all the keys in %dic, and is therefore not itself a key of %dic. What you actually meant was:
$line =~ s%$matchkey%$dic{$&}%g; # Use the matched string as a key +in $dic $line =~ s%($matchkey)%$dic{$1}%g; # Same as above without the perfor +mance issues of $&
See the relevant section of perlvar.

Replies are listed 'Best First'.
Re^2: Multiline Regex replacement in Multiline file
by Athanasius (Archbishop) on Sep 15, 2014 at 09:37 UTC

    Hello Grimy,

    This is a nice idea, but unfortunately, as long as the regex contains metacharacters, it can’t be made to work, because $1 will never contain those metacharacters:

    #! perl use strict; use warnings; use Data::Dump; my $re = 'aaa\s+bbb'; my %dic = ($re => 'new'); my $s = 'aaa bbb'; $s =~ s/($re)/$dic{$1}/; print "\$1 = $1\n"; print "\$s = $s\n"; print "\%dic = "; dd \%dic;

    Output:

    19:34 >perl 1011_SoPW.pl Use of uninitialized value within %dic in substitution iterator at 101 +1_SoPW.pl line 10. $1 = aaa bbb $s = %dic = { "aaa\\s+bbb" => "new" } 19:34 >

    Sorry, :-(

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Hello Athanasius, Is there any workaround for this ? as my regex file is a long one and also i need to process a lot of files, so its kind of time/cpu consuming. I want to get rid of "for" loop as mentioned in reply to your previous post

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (6)
As of 2024-04-19 06:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found