Re: Parsing a text file with mutuple seperator

[email protected] Tue, 8 Apr 2008 17:28:36 -0700 (PDT)
Newsgroups perl.scripts
Organization http://groups.google.com
Message-ID <7417fec1-d6ee-48ef-863e-ab75ce5df336@a70g2000hsh.googlegroups.com>
Yes Brad,

I have tried the Text::ParseWords and that is exactly what I am
looking for.

Thanks

On Apr 8, 8:39=A0pm, [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:
> > "" =A0 "This is 2nd field"
> > 3 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A04
> > 1 =A0 =A02
> > "" =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 4
> > 1 =A0 =A02 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 "The fiel=
d may consist of (meta)
> > characters" =A0 ""
>
> > What I am doing is as such:
> > =A0 while ($line=3D~/(".*?")/) {; =A0 =A0 =A0 =A0 =A0 =A0 <- Loops until=
 all double-
> > quoted string is replaced
> > =A0 =A0 =A0$line=3D~s/""/__EMPTY__/g;
> > =A0 =A0 =A0$tmp1=3D$1;
> > =A0 =A0 =A0$tmp2=3D$1;
> > =A0 =A0 =A0$tmp1=3D~s/"//g;
> > =A0 =A0 =A0$tmp1=3D~s/ /__SPACE__/g;
> > =A0 =A0 =A0$tmp2=3D~s/([\(\)])/\\$1/g;
> > =A0 =A0 =A0$line=3D~s/$tmp2/$tmp1/; =A0 =A0 =A0 =A0 =A0 =A0<- needs to r=
eplace meta-
> > characters in $tmp2
> > =A0 }
> > =A0 @tmp=3Dsplit /\s+/, $line;
> > =A0 foreach $i (0..$#tmp) {
> > =A0 =A0 =A0$tmp[$i]=3D~s/__SPACE__/ /g;
> > =A0 =A0 =A0$tmp[$i]=3D~s/__EMPTY__//g;
> > =A0 =A0 =A0// Store data
> > =A0 }
>
> > 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- Hide quoted text -
>
> - Show quoted text -