Rob Dixon wrote:
> Ravi Malghan wrote:
>> Hi: I am trying to extract some stuff from a string and not getting the 
>> expected results. I have looked through 
>> http://www.perl.com/doc/manual/html/pod/perlre.html and can't seem to figure 
>> this one out.
>>
>> I have a string which is a sequence of words and each item is comma seperated
>> field1, lengthof value1, value1,field2, length of value2, 
>> value2,field3,length of value3, value3 and so on
>>
>> After each field name I have the length of the value
>>
>> I want to split this string into an array using comma seperator, but the 
>> problem is some values have one or more commas within them.
>>
>> so for example my string might look like this
>>
>> $origString = "EMPLID,4,9066,USERID,7,W3LWEB1,TEXT,54,This is a test note, 
>> with some commas, and more commas,ADDR,3515421 Test Lane, Rockville, MD, 
>> USA,ESCALATION-LVL,1,0"
>>
>> My current code goes character by character and constructs what I want. But
>> is very slow when this string gets large.
> 
> The program below will do what you describe.

Here's an improvement that explains when it doesn't find values that it expects.

Rob


use strict;
use warnings;

my $origString = "EMPLID,4,9066,USERID,7,W3LWEB1,TEXT,54,This is a test note,
with some commas, and more commas,ADDR,35,15421 Test Lane, Rockville, MD,
USA,ESCALATION-LVL,1,0";

while() {

  $origString =~ /\G([^,]+),(\d+),/g or die "No field name / size found";
  my ($field, $size) = ($1, $2);

  $origString =~ /\G(.{$size})/g or die "Insufficient characters for field 
size";
  my $value = $1;

  printf "%s (%d) - %s\n", $field, $size, $value;

  $origString =~ /\G,/g or last;
}

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to