Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Oct 2002
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Splitting a variable???

    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!

  • #2
    New Coder
    Join Date
    Sep 2002
    Location
    Up North (UK)
    Posts
    46
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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
    Code:
    $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. 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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •