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:  <%-{-{-{-<