0

There is a string as:

$string= 123456-9876;

Need to split it in array as follows:

$string = [12,34,56,98,76]

trying to split it as split('-',$string) is not serving the purpose. How could i do that in perl?

4
  • Do you want to split it into 2-digit substrings? Commented Dec 3, 2018 at 15:38
  • 3
    Instead of splitting, match what you want to keep: $string = [ $string =~ /(\d\d)/g ] Commented Dec 3, 2018 at 15:40
  • how about this? ([^-].) Commented Dec 3, 2018 at 15:42
  • What is the rule for splitting? Commented Dec 3, 2018 at 15:43

2 Answers 2

5

Extract pairs of digits: (e.g. "1234-5678"[12,34,56,78])

$string = [ $string =~ /\d\d/g ];

Extract pairs of digits, even if separated by non-digits: (e.g. "1234-567-8"[12,34,56,78])

$string = [ $string =~ s/\D//rg =~ /../sg ];
Sign up to request clarification or add additional context in comments.

Comments

1

Rather than splitting, you can capture all 2 digit numbers with this perl code,

$str =  "123456-9876";
my @matches = $str =~ /\d{2}/g;

print "@matches\n";

Prints,

12 34 56 98 76

Another solution, that just groups two digits no matter whatever, wherever non-digits are present in the string, without mutating the original string

$string =  "1dd23-dsd--456-9-876";
while($string =~ /(\d).*?(\d)/g) {
        print "$1$2 ";
}

Prints,

12 34 56 98 76

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.