split operator with quoted strings

A

arasu

Hi,

#!/usr/local/bin/perl -w

use strict;

my $x = 'hello goat "world world world" "fox goat"';

my @x = split ( /\s+/, $x );

foreach ( @x )
{
print "$_\n";
}

======================

This splits on space, but expected output is
"string within quotes should not be split."

hello
goat
"world world world"
"fox goat"
 
J

John W. Krahn

#!/usr/local/bin/perl -w
use strict;

my $x = 'hello goat "world world world" "fox goat"';

my @x = split ( /\s+/, $x );

foreach ( @x )
{
print "$_\n";
}

======================

This splits on space, but expected output is
"string within quotes should not be split."

hello
goat
"world world world"
"fox goat"


$ perl -le'
my $x = q/hello goat "world world world" "fox goat"/;
@f = $x =~ /"[^"]+"|\S+/g;
print for @f;
'
hello
goat
"world world world"
"fox goat"



John
 
P

Perusion hostmaster

Hi,

#!/usr/local/bin/perl -w

use strict;

my $x = 'hello goat "world world world" "fox goat"';

my @x = split ( /\s+/, $x );

foreach ( @x )
{
print "$_\n";
}

======================

This splits on space, but expected output is
"string within quotes should not be split."

hello
goat
"world world world"
"fox goat"

Easy with a standard module:

use Text::parseWords qw/quotewords/;

my $x = 'hello goat "world world world" "fox goat"';

my @x = quotewords('\s+', 1, $x);

print join "\n", @x, '';

The second parameter to quotewords() tells it to keep the quotation
marks, set it to zero to not retain them.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top