Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

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
Re: Pattern matching
by choroba (Abbot) 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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1016479]
Approved by vinoth.ree
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2014-07-26 14:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (177 votes), past polls