Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Pattern matching

by perlCrazy (Monk)
on Feb 01, 2013 at 09:08 UTC ( #1016479=perlquestion: print w/replies, xml ) Need Help??
perlCrazy has asked for the wisdom of the Perl Monks concerning the following question:

have file which has line like this:
123,abc1,test1,"1,3,5",new,"abc,dfg,hj" 124,abc2,test2,"1,3,5",new,"abc,dfg,hj" 125,abc3*,test3,"*|1,3,5",new,"abc,dfg,hj"
Value of each line has field which is ',' delimited. Field which starts with double quotes(") is one filed which itself is comma delimited.
Is there anyway to replace the ',' with some other value ~ while reading each line between double quotes (") ? Thanks for help.

Replies are listed 'Best First'.
Re: Pattern matching
by choroba (Bishop) on Feb 01, 2013 at 09:33 UTC
    Seems like a work for Text::CSV. Does this produce the expected output?
    #!/usr/bin/perl use warnings; use strict; use Text::CSV; my $csv = Text::CSV->new; open my $FH, '<', '1.csv' or die $!; while (my $row = $csv->getline($FH)) { s/,/~/g for @$row; $csv->combine(@$row); print $csv->string, "\n"; }
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Pattern matching
by tmharish (Friar) on Feb 01, 2013 at 10:16 UTC
    If you WANT to use RegEx then:
    use strict; use warnings ; my @csv = <DATA>; foreach my $line ( @csv ) { my $clean_line = $line ; while( $line =~ /"(.*?)"/g ) { my $match = $1 ; my $match_cleaned = $match ; $match_cleaned =~ s/,/~/g; my $location = index( $line, $match ) ; my $clean_line = substr( $clean_line, $location, length( $match ), + $match_cleaned ); } print "$clean_line"; } __DATA__ 123,abc1,test1,"1,3,5",new,"abc,dfg,hj" 124,abc2,test2,"1,3,5",new,"abc,dfg,hj" 125,abc3*,test3,"*|1,3,5",new,"abc,dfg,hj"

    Notice that replace withing $line is not done using a regex - this is to avoid escaping $match and to also speed things up.

    You can compress this code but its been stretched out for readability.

      Yes, and pray for \" not appearing in the data.
      لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
        Thanks for help and input. below code works fine:
        my $file = "t.txt"; open(FH,$file) || die "can't open file \n"; while (<FH>) { chomp; my $line = $_; $line =~ s/\"(.*?)\"/replace($1)/ge; $line =~ s/\,/~/g; $line =~ s/\;/,/g; print "$line \n"; } close FH; sub replace { my ($str) = @_; $str =~ s/\,/\;/g; return $str; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1016479]
Approved by vinoth.ree
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2018-06-24 22:31 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.