Re: Parsing a text file with mutuple seperator
[email protected] (Otavio) Tue, 8 Apr 2008 06:08:44 -0700 (PDT)
| Newsgroups | perl.scripts |
|---|---|
| Organization | http://groups.google.com |
| Message-ID | <f95a8b6a-1962-4338-8b4c-1f3378d794fe@f63g2000hsf.googlegroups.com> |
Either you use the module mentioned or try a multi stage split. It=B4s
uglier but is a way to get the work done.
First I=B4d split he data by ("\s+\"") then by ("\"\s+") then I=B4d deal
with the tabs....
Just my two cents. ;-)
On 8 abr, 09:39, [email protected] (Brad Baxter) wrote:
> If I were you, I'd use Text::ParseWords::parse_line()
>
> On Mon, Apr 7, 2008 at 9:11 PM, <[email protected]> wrote:
> > Hi all,
>
> > I am writing a perl script to parse a file. The data in the file is
> > seperated by space/tab. However, certain fields may be empty or
> > consist of mutiple words and are double quoted and this makes it
> > difficut for me to do a split.
>
> > Example of data:
> > "" "This is 2nd field"
> > 3 4
> > 1 2
> > "" 4
> > 1 2 "The field may consist of (meta)
> > characters" ""
>
> > What I am doing is as such:
> > while ($line=3D~/(".*?")/) {; <- Loops until all double-
> > quoted string is replaced
> > $line=3D~s/""/__EMPTY__/g;
> > $tmp1=3D$1;
> > $tmp2=3D$1;
> > $tmp1=3D~s/"//g;
> > $tmp1=3D~s/ /__SPACE__/g;
> > $tmp2=3D~s/([\(\)])/\\$1/g;
> > $line=3D~s/$tmp2/$tmp1/; <- needs to replace meta-
> > characters in $tmp2
> > }
> > @tmp=3Dsplit /\s+/, $line;
> > foreach $i (0..$#tmp) {
> > $tmp[$i]=3D~s/__SPACE__/ /g;
> > $tmp[$i]=3D~s/__EMPTY__//g;
> > // Store data
> > }
>
> > Substitue "" with __EMPTY__
> > While line matches ".*?" (non-greedy match), remember the content
> > between the quotes.
> > Assign this content to $tmp1 and $tmp2. Remove " from $tmp1, Replace '
> > ' with __SPACE__.
> > Replace metacharacters of $tmp2 with escape, ie (meta) to \(meta\).
> > Substition of $tmp2 with $tmp1 (non-global).
> > Do a split /\s+/,
> > Replace __EMPTY__ with empty string
> > Replace __SPACE__ with " ".
>
> > Does you one have a neater and more efficient way either by split of
> > regexp?
>
> > Thanks
> > Shu Teng