Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I am writing a program to rename variables in VB code. I generate a hash of new names keyed by the current names. I want to replace all instances of the old name by the new name except where they appear in strings or comments.
Some notes on VB:
- In VB double quotes are put into a string by using two of them: "This is a doube quote""."
- Comments start at "'" and contine until the end of the line
The program builds up the list of renames as is reads the code line by line. The renames are performed on each line after it is processed. Is there a better way to perform the renaming?
Output:use strict; use warnings; my $renames = { this_sub => 'that_sub', var_1 => 'var_a', var_2 => 'var_b', Ignore => 'FAILED', nothing => 'FAILED', and => 'FILED', can => 'FAILED', t => 'FAILED', do => 'FAILED', it => 'FAILED', }; my $line = qq/ this_sub("first", var_1, "Ignore ""can't""", var_2) ' + do it\n/; print $line; my $matched_keys = '\b' . join( '|', keys %$renames ) . '\b'; my $match = qr/($matched_keys)/; my $vb_string = qr/("[^"]*(?:""[^"]*)*")/; my @parts = split $vb_string, $line; my $do_code = 0; for my $part (@parts) { $do_code = !$do_code; next unless $do_code; if ( $part =~ m/'/ ) { my ( $code, $comment ) = split /'/, $part, 2; $code =~ s/$match/$renames->{$1}/ge; $part = "$code'$comment"; last; } else { $part =~ s/$match/$renames->{$1}/ge; } } print join( "", @parts )
this_sub("first", var_1, "Ignore ""can't""", var_2) ' do it that_sub("first", var_a, "Ignore ""can't""", var_b) ' do it
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Replacing words in VB code but not strings or comments
by AnomalousMonk (Archbishop) on Sep 27, 2013 at 20:49 UTC | |
by Anonymous Monk on Sep 27, 2013 at 21:56 UTC | |
Re: Replacing words in VB code but not strings or comments (5.8/10 versions)
by AnomalousMonk (Archbishop) on Sep 28, 2013 at 02:30 UTC | |
Re: Replacing words in VB code but not strings or comments (Simplified versions)
by AnomalousMonk (Archbishop) on Sep 28, 2013 at 19:45 UTC |
Back to
Seekers of Perl Wisdom