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

Re: Add Quotes to entries in a file

by johngg (Canon)
on Jul 12, 2018 at 18:05 UTC ( [id://1218397]=note: print w/replies, xml ) Need Help??


in reply to Add Quotes to entries in a file

A solution using split, a single substitution on an array slice then a join.

johngg@abouriou ~/perl/Monks $ perl -Mstrict -Mwarnings -E ' open my $inFH, q{<}, \ <<__EOD__ or die $!; ABC;123;;;;;HELLO; DEF;345;;BANANA;12DEF;44,55;4*12;;;;;;;;3; __EOD__ my $outFile = do { \ my $dummy; }; open my $outFH, q{>}, $outFile or die $!; while ( <$inFH> ) { my @items = split m{;}; s{(.*)}{"$1"} for @items[ 1 .. ( $#items - 1 ) ]; print $outFH join q{;}, @items; } print $$outFile;' ABC;"123";"";"";"";"";"HELLO"; DEF;"345";"";"BANANA";"12DEF";"44,55";"4*12";"";"";"";"";"";"";"";"3";

I hope this is of interest.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Add Quotes to entries in a file
by AnomalousMonk (Archbishop) on Jul 12, 2018 at 18:39 UTC

    No substitution is necessary since you're just wrapping double-quotes around strings. Also, in the pure-string version, a split LIMIT of -1 is needed to capture a final empty | empty string field for later re-join-ing; in the file-based version, the final field is a newline, which gets very neatly join-ed back on.

    c:\@Work\Perl\monks>perl -wMstrict -le "my @strings = ( 'ABC;123;;;;;HELLO;', 'DEF;345;;BANANA;12DEF;44,55;4*12;;;;;;;;3;', ); ;; for my $s (@strings) { printf qq{'$s' \n>}; my @items = split m{;}, $s, -1; $_ = qq{\"$_\"} for @items[ 1 .. ( $#items - 1 ) ]; print join(q{;}, @items), qq{< \n}; } " 'ABC;123;;;;;HELLO;' >ABC;"123";"";"";"";"";"HELLO";< 'DEF;345;;BANANA;12DEF;44,55;4*12;;;;;;;;3;' >DEF;"345";"";"BANANA";"12DEF";"44,55";"4*12";"";"";"";"";"";"";"";"3" +;<


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2024-04-23 07:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found