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' $!";
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> ) {
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)/ ) {
$j++;
if ($j > 255) {
The OP wanted to go from 0 to 255 but this goes from 0 to 254.
$j = 0;
$i++;
}
}
print $OUTFILE $line;
}
John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity. -- Damian Conway
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/