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:
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |