There are a bunch of errors and dodgy practices there. The first thing that you need to do is add strictures:
use strict;
use warnings;
Then you need to declare all the variables you use by prefixing them with my. For example:
my $input_file = "dump.vcd";
You should always use the three parameter version of open to improve code readability and reduce possible errors of various sorts:
open INPUT, '<', "$input_file";
The while loop is reading one line at a time so you don't need a for loop (see perlsyn - foreach) to iterate over anything - $efile is not an array.
In your regex you use a character set ([!,\#,\",\$,\%,&]), but it isn't what you possibly expect. The characters included in the set are !,#"$%& which includes comma, that may surprise you. Note that none of the quoted characters in the set need to be quoted.
The complete code rewritten and modified to take itself (on my system) as the input looks like:
#!/usr/bin/perl
use strict;
use warnings;
my $input_file = "noname1.pl";
open INPUT, '<', "$input_file";
while (my $efile = <INPUT>) {
$efile =~ s/\$var\w \d+ ([!,\#,\",\$,\%,&]) (\w) \$end/\$var $1 $2
+/;
print $efile;
}
close INPUT;
__DATA__
$var1 1 , x $end
$varx 2 ! _ $end
$vary 3 # aa $end
prints:
#!/usr/bin/perl
use strict;
use warnings;
my $input_file = "noname1.pl";
open INPUT, '<', "$input_file";
while (my $efile = <INPUT>) {
$efile =~ s/\$var\w \d+ ([!,\#,\",\$,\%,&]) (\w) \$end/\$var $1 $2
+/;
print $efile;
}
close INPUT;
__DATA__
$var , x
$var ! _
$vary 3 # aa $end
Note that I added the __DATA__ (see perldata - Special Literals) section so I could include something for the regex to match.
DWIM is Perl's answer to Gödel
|