Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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.

Comment on Pattern matching
Download Code
Replies are listed 'Best First'.
Re: Pattern matching
by choroba (Canon) 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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2015-11-28 20:03 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (744 votes), past polls