On Fri, Jun 20, 2008 at 3:10 PM, Ravi Malghan <[EMAIL PROTECTED]> 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.
> TIA
> Ravi

My solution:

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,3515421 Test Lane,
Rockville, MD, USA,ESCALATION-LVL,1,0";

my @arr = split (/,/, $origString);
# print join ("\n", @arr); exit;

while ( scalar @arr ) {

    my $field = shift @arr;
    last unless ( defined $field );

    my $vlength = shift @arr;
    last unless ( defined $vlength );
    unless ( $vlength =~ /^\d+$/ ) {
        die "Invalid length: [$vlength]\n";
    }

    my $value = "";
    while ( length ( $value ) < $vlength ) {
        my $bit = shift @arr;
        last unless ( defined $bit );

        $value .= "," if ( length $value );
        $value .= "$bit";
    }
    print "$field -> $value\n";
}

Time it?

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


Reply via email to