Thread: Perl Split

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2012
    Posts
    31
    Rep Power
    3

    Perl Split


    Hi

    I am trying to split a string which is :

    3dfhg4-fged-3eft-fgretgyt

    basically want to split a string which has 3 "-"

    Thanks
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,930
    Rep Power
    1225
    You can use a regex or the split function.

    What have you tried?
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    830
    Rep Power
    496
    Simply try this:

    Perl Code:
    my @array_of_strings = split /-/, "3dfhg4-fged-3eft-fgretgyt";
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2012
    Posts
    31
    Rep Power
    3
    Thank you for the reply.

    I am trying to use a if cluase in a script where if the string matches 3 "-" than to do something.

    If I use the split function not sure how I can still see if the string has 3 "-".

    Because I do have some strings which only have 2 "-".

    Thanks-
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,930
    Rep Power
    1225
    You have several options.

    1) Use a regex to capture the fields. Something like this:
    Code:
    my $str = '3dfhg4-fged-3eft-fgretgyt';
    
    if ( $str =~ /^([^-]+)-([^-]+)-([^-]+)$/ ) {
        # the 3 captured fields are in $1 $2 and $3
        # process them as needed
    }
    else {
        # do something else
    }
    2) You can use the split function like Laurent has shown and then count the number of elements in the array to verify that you have the correct number

    3) You can use the tr operator to count the number of hyphens in the string and then make your branching decision on that count. Something like this:
    Code:
    if ( $str =~ tr/-// == 3 ) {
        # do the split
    }
    else {
        # do something else
    }
    Last edited by FishMonger; May 5th, 2013 at 10:35 AM. Reason: fixed the regex

IMN logo majestic logo threadwatch logo seochat tools logo