Hello, I am wanting code that replaces newlines or carriage returns with the charachter \n. The following code will do this:
use strict;
$_=<<'_quote_';
hai xtest "aa xx
aax" baix "xx"
x "axa\"x\\" xa "x\\\
\\"x" ax
xbai!x
_quote_
print "Original:\n", $_, "\n";
s/
(
(?:
# at the beginning of the string match till inside the quotes
^(?&outside_quote) "
# or continue from last match which always stops inside quotes
| (?!^)\G
)
(?&inside_quote) # eat things up till we find what we want
)
\r?\n # the thing we want to replace
(
(?&inside_quote) # eat more possibly till end of quote
# if going out of quote make sure the match stops inside them
# or at the end of string
(?: " (?&outside_quote) (?:"|\z) )?
)
(?(DEFINE)
(?<outside_quote> [^"]*+ ) # just eat everything till quoting star
+ts
(?<inside_quote> (?:[^"\\\r\n]++|\\.)*+ ) # handle escapes
)
/$1\n$2/xg;
print "Replaced:\n", $_, "\n";
However, I want to be able to do this for a file that I read in (*.csv). For example, if I use the follwing to read the same file into $_, it does not work:
my $file="testdata.csv";
open(FILE, $file) or
die "Can't open $file: $!\n";
select((select(FILE), $/ = undef)[0]);
$_=<FILE>
Any ideas? And, no I am not able to use the Perl packages Spreadsheet::****
Here, testdata.csv is this business:
hai xtest "aa xx
aax" baix "xx"
x "axa\"x\\" xa "x\\\
\\"x" ax
xbai!x
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.