in reply to Re: Replace only selected characters
in thread Replace only selected characters

Hi, Im struggling to Use this against a csv file with several lines of lines like this which needs formatting.
open(FILE, "<ABC.csv"); @lines = <FILE>; print @lines; print $lines[1]; close(FILE); foreach ($lines) { $lines = ~ s/(?<=,)([^,]*),/\1/g; print("$lines \n"); }
what am I doing wrong now :(

Replies are listed 'Best First'.
Re^3: Replace only selected characters
by AnomalousMonk (Archbishop) on Oct 16, 2011 at 02:08 UTC
    foreach ($lines) { $lines = ~ s/(?<=,)([^,]*),/\1/g; print("$lines \n"); }

    In addition to the fact that the scalar  $linesdoesn't appear to be defined anywhere (you are using warnings and strictures, aren't you?), the statement
        $lines = ~ s/(?<=,)([^,]*),/\1/g;
    should probably be
        $lines =~ s/(?<=,)([^,]*),/$1 /g;
    (the  =~ operator should have no space between = and ~, use  $1 instead of  \1 in the replacement string, there should actually be a space somewhere in the replacement string if you want to replace a ',' with a space). I would suggest something like (untested):

    foreach my $line (@lines) { $line =~ s/(?<=,)([^,]*),/$1 /g; print("$line \n"); }

    Update: After further inspection of the OP and replies, it appears that rohanan wants every ',' after the first replaced with the empty string rather than with a space. So (still untested):
        $line =~ s/(?<=,)([^,]*),/$1/g;

Re^3: Replace only selected characters
by Anonymous Monk on Oct 14, 2011 at 23:23 UTC

    Hi,

    'foreach ($lines) {' -
    should this be 'foreach (@lines) {' ?

    And so on

    J.C.