user3799576 user3799576 - 1 month ago 5
Perl Question

How do I split a string using a regular expression in Perl?

I have a string in Perl:

'CCCCCCCC^hC^iC^*C^"C^8A'
.

I want to split this string using a regular expression:
"^[any_character]C"
. In other words, I want to split it by the actual character
^
, followed by any character, followed by a specific letter (in this case
C
, but it could be
A
, or any other character).

I have tried looking at other questions/posts and finally came up with my
@split_str = split(/\^(\.)C/, $letters)
, but this seems not to be working.

I'm sure I'm doing something wrong, but I don't know what.

Answer

You were very close. There were just a couple of errors in your code. Before I explain them, here's the code I was using to test solutions.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Data::Dumper;

$_ = 'CCCCCCCC^hC^iC^*C^"C^8A';

my @data = split /\^(\.)C/;

say Dumper @data;

Running this with your original regex, we get this output:

$VAR1 = 'CCCCCCCC^hC^iC^*C^"C^8A';

No splitting has taken place at all. That's because your regex includes \.. The dot matches any character in a string, but by escaping it with the backslash you have told Perl to treat it as an ordinary dot. There are no dots in your string, so the regex doesn't match and the string is not split.

If we remove the backslash, we get this output:

$VAR1 = 'CCCCCCCC';
$VAR2 = 'h';
$VAR3 = '';
$VAR4 = 'i';
$VAR5 = '';
$VAR6 = '*';
$VAR7 = '';
$VAR8 = '"';
$VAR9 = '^8A';

This is better. Some splitting has taken place. But because we have parentheses around the dot ((.)), Perl has "captured" the characters that the dot matches and added them to the list of values that split() returns.

If we remove those parentheses, we get only the values between the split markers.

$VAR1 = 'CCCCCCCC';
$VAR2 = '';
$VAR3 = '';
$VAR4 = '';
$VAR5 = '^8A';

Note that we get a few empty elements. That's because in places like "^hC^iC" in your string, there is no data between two adjacent split markers.

By moving the parentheses around the whole of the regex (split /(\^.C)/), we can get a list which includes all of the split markers together with the data between them.

$VAR1 = 'CCCCCCCC';
$VAR2 = '^hC';
$VAR3 = '';
$VAR4 = '^iC';
$VAR5 = '';
$VAR6 = '^*C';
$VAR7 = '';
$VAR8 = '^"C';
$VAR9 = '^8A';

Which of these options is most useful to you depends on exactly what you're trying to do.