Log in Page Discussion History Go to the site toolbox

Markrh:PerlProgramming:ParsingQuotes

From BluWiki

Code, quotes.pl

#!perl -w
use strict;

# Parse a string for quoted and non-quoted values.
# I think Rob Hoeting emailed this to me about 10 years ago.

my (@tmp);
$_ = 'one and "two and" 3 " and four and five" and six and 0';

print "\$_: [$_]\n";
while($_){
    # check for non-greedy match for a quoted string
        #  at beginning of string
        if (/^ *(".*?")/){     
                push(@tmp,$1);     # add match to array
                $_ = $';           # assign trailing non-matched string to $_
        }
        # else check for an unquoted match at
        #  beginning of string
        elsif (/^ *(\S+)/){
                push(@tmp,$1);     # add match to array
                $_ = $';           # assign trailing non-matched string to $_
        }
}

my $i=0;
foreach(@tmp){
        $i++;
        print "$i $_\n";
}

Output

./quotes.pl
$_: [one and "two and" 3 " and four and five" and six and 0]
1 one
2 and
3 "two and"
4 3
5 " and four and five"
6 and
7 six
8 and
9 0

Perl Programming, Cookbook

Site Toolbox:

Personal tools
GNU Free Documentation License 1.2
This page was last modified on 12 September 2005, at 14:49.
Disclaimers - About BluWiki