Thanks for the tips! More comments below. On Tue, Nov 3, 2009 at 4:10 AM, John W. Krahn <jwkr...@shaw.ca> wrote:
> tom smith wrote: > >> On Mon, Nov 2, 2009 at 7:41 PM, Remy Guo <rollingst...@gmail.com> wrote: >> >> i've got problem when trying to perform a substitution. >>> >>> the text file i want to process is like this: >>> ... >>> XXXXXX { >>> ABDADADGA >>> afj*DHFHH >>> } (a123) >>> XXDFAAF { >>> af2hwefh >>> fauufui >>> } (b332) >>> ... >>> >>> i want to match the content in the parenthesis (a123 and b332, here) and >>> replace them with a sorted number (0;0, 0;1, 0;2, .... 0; 255, 1;0, >>> 1;1, ...1; 255, for example), so i wrote the script like this: >>> if (m/\}.*\(.*\)/) >>> { >>> $j++; >>> if ($j >= 255) >>> { >>> $i++; >>> $j = 0; >>> } >>> >>> $_ =~ s/\(.*\)/$i;$j/ >>> } >>> >>> now the problem is that, i'm sure the matching >>> regex successfully matches the line that i want, but the subsitution just >>> don't happen. why?... >>> >> >> First, the s/// operator applies to $_ by default. >> >> Second, as far as I can tell there's no indication anywhere in your script >> as to what the value of $_ might be. >> >> This works for me: >> >> use strict; >> use warnings; >> >> open(my $INFILE, "<", "in.txt"); >> open(my $OUTFILE, ">", "out.txt"); >> > > You should *always* verify that the files have been opened correctly before > trying to use a possibly invalid filehandle. > > open my $INFILE, '<', 'in.txt' or die "Cannot open 'in.txt' $!"; > open my $OUTFILE, '>', 'out.txt' or die "Cannot open 'out.txt' $!"; Whoops! > > > > my $line; >> my $i = 0; >> my $j = 0; >> >> while ($line = <$INFILE>) { >> > > There is no need for $line to be in file scope: > > while ( my $line = <$INFILE> ) { > > Shoot. Normally, I write it like you did, but I saw it written the other way somewhere, and I thought it looked cleaner. I'll do it your way from now on. > > if ($line =~ /\((.*?)\)/) { >> >> $line =~ s/$1/$i;$j/; >> > > If you have two regular expressions that are doing the same thing then you > are probably doing it incorrectly: > > if ( $line =~ s/\((.*?)\)/($i;$j)/ ) { > Ah. Nice. > > $j++; >> if ($j > 255) { >> > > The OP wanted to go from 0 to 255 but this goes from 0 to 254. > > >> Yes. You're wrong, though about what my code does. The if statement doesn't evaluate to true unless $j == 256. Thanks for the suggestions. I appreciate it.