chriso has asked for the wisdom of the Perl Monks concerning the following question:

My script involves opening a data file which has the following format:

q1:The cow jumped over the moon a1:a,b,c s1:a,first,b,second,c,third

a1 is an array and s1 is a hash. I want to make things as easy as possible for those who will be creating the data file. Currently, for the script to work there can be no spaces between the commas and the next letter/word.

a1:a,e will work but a1:a, e will not because of the space between the comma and the e.

I am using the following format to make the array: my @array = split (/,/, $value); and my %hash = split (/,/, $value); to create the hash.

I have also tried using split like this: split(/,\s*/, $value) but that didn't work either.

Is there a good way to create both of these that will ignore any spaces in those records?

Say a user creates a record like this:

a1: c, d s1:a, first, b, second, c, third

where he/she inadvertantly puts one or more spaces between the comma and the next letter/word.

Thanks for the input.

Chris

Replies are listed 'Best First'.
Re: clearing spaces from data input
by jryan (Vicar) on Jan 02, 2002 at 02:01 UTC

    Try using this regex to strip out the spaces around commas before you do your parsing:

    $blah =~ s/\s*(,)\s*/$1/g;
Re: clearing spaces from data input
by Juerd (Abbot) on Jan 02, 2002 at 01:54 UTC
    You said you have tried split /,\s*/, but that it didn't work. In that case your computer or your perl is severely broken.

    By the way, maybe you should consider using standard CSV or another well-known method of having plain text data (XML? YAML?)

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Re: clearing spaces from data input
by mrbbking (Hermit) on Jan 02, 2002 at 05:50 UTC
    From your example, it looks like spaces are not allowed at all in a1 or s1. If all you really want to do is strip out spaces, this'll do the trick:
    $line = "s1:a,first,b, second, c,third"; $line =~ s/ //g; #print $line;
    jryan's code is careful to remove only spaces next to commas. But if you want to remove all spaces, s/ //g; is what you want. Well, it's what I would want, anyway...