Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Split 1

Status
Not open for further replies.

dietmarp

Programmer
Dec 27, 2001
53
US
Hi,

following situation I ran into -

my $values=(value1 "value two" value3 "value four)

How can I split to receive following result

value1
value two
value3
value four

to be able to compute them.

I had in my script

my @lines = split(/ /,$values);
foreach (@values){
....
}
but this fails of course

Thanks - Dietmar

 
Hi,

Your $values data seems a little inconsistent. Does all your data look like this? Anyway, heres a couple of examples which may help you...

Code:
my $values = qq(value1 "value two" value3 "value four");
my @lines = split(/ /,$values);
foreach (@lines){
	print "$_\n";
}

OUTPUT:
value1
"value
two"
value3
"value
four"

Code:
my @values = ("value1","value two","value3","value four");
foreach (@values){
	print "$_\n";
}

OUTPUT:
value1
value two
value3
value four

Code:
my $values = qq("value1" "value two" "value3" "value four");
my @lines = split(/\"/,$values);
foreach (@lines){
	unless ($_ eq " ") {
		print "$_\n";
	}
}

OUTPUT:
value1
value two
value3
value four

Chris
 
A slight improvement to example 3:

Code:
unless (($_ eq "") || ($_ eq " ")){

Another example which uses your data pretty much exactly as you wrote it:

Code:
my $values = 'value1 "value two" value3 "value four';
my @lines = split(/\"/,$values);
foreach (@lines){
	#Remove white space from beginning/end of each line
	$_ =~ s/^\s+//;
	$_ =~ s/\s+$//;
	print "$_<br>";
}

Chris
 
is value four really like that?

"value four

if its always on the end that should be possible but if you have a field with one double-quote somewhere else in the line/string that will really mess everything up.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
thanks for your input
I managed to have the values separated by "|"
e.g.
my $values = (value1 | "value two" | value3 | "value four);

- now I can process them properly.
As Kevin states - one double-quote to much - end there is a mess

Cheers - Dietmar

 
Ah good. My next solution would have been to replace all the spaces which were not wrapped within quotes (" "), with another split character such as | as those spaces within whole values were a bit of a problem, although the last value would require a little extra code. It was best the way you eventually did it.

Chris
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top