PDA

View Full Version : Splitting a variable???



MadhatterWales
10-05-2002, 09:32 PM
I'm trying to write a script that will take the input from a formfield and split the result into different variables. E.g.

AB123QW12

is split into:

Variable 1: AB
Variable 2: 123
Variable 3: QW
Variable 4: 12

But how can I do this in perl/cgi?? I've looked through 2 - 3 books and can't find anything - please, please help!

fivesidecube
10-06-2002, 12:04 PM
MadhatterWales,

You need to be looking at regular expressions. If your input string is always a consistant pattern, then you can code a single expression to unpick the whole pattern, but if the input varies in pattern, then some form of loop will be required.

An example of some code handling your example is
$TestString="AB123QW12";
$TestString =~ /^(\D)+(\d)+(\D)+(\d)+$/;
$Variable1 = $1;
$Variable2 = $2;
$Variable3 = $3;
$Variable4 = $4;

Please forgive an errors in this, I've just written it and I don't have any compilers installed to test it! Please note, I often place the '+' character inside of the ')' when they should be outside. So if this doesn't work, try moving the '+' characters inside the ')' character.

The /^(\D)+(\d)+(\D)+(\d)+$/ string is the regular expression that unpicks the $TestString scalar. More information on what this regular expression is doing can be found here (http://www.perldoc.com/perl5.6.1/pod/perlre.html). A side effect of this instruction, is to set scalars $1..9 to the different matched patterns in each of the '(' and ')'.

I hope this helps,

Fivesidecube.