perl parsing inserting new line and ^M -
i trying modify few strings in file using perl using below logic..
open file1, "< /tmp/sam.dsl" //in read mode open file2, "> /tmp/sam2.dsl" // open in write mode while(<file1>) if($_=s/string/found/g) push file2, $_... i able change contents when read file has ^m in it..
my datafile of below format
name 'sample' i change to
name 'sample2' currently code changes
name 'sample2 ' which creates new line , replacement.
do need use anyother mode open file write..?
my guess is, working linux file on windows. perl automatically converts \n \r\n on dos-compatible machines after reading , before writing. rid of behaviour, can use binmode <file> on filehandles, sets filehandle "raw binary mode". if want use other layers (like :utf8 or :encoding(utf-8)) not enabled, , might want set them yourself, if handling character data. use perlio::eol module cpan.
consider looking @ these documentation pages:
- perlio general understanding how perl-io works.
- open pragma (not function) set layers 1 program.
- binmode function might want consider.
my suggestion, can't test (no windows around), use following:
open $outfile, '<:encoding(utf-8)', "filename" or die "error opening: $!"; binmode $outfile, join '', grep {$_ ne ':crlf'} perlio::get_layers($outfile) or die "error setting output:\n $!" while(<$infile>){ s/match/replacement/g; print $outfile $_; }
Comments
Post a Comment