Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: Replace only selected characters

by rohanan (Novice)
on Oct 14, 2011 at 21:41 UTC ( [id://931588]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://931588]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-18 09:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found