In Perl, not every string problem needs a regular expression.
If you know where something is in a string,
substr STRING, OFFSET, LENGTH
my $s = "PerlIsFun"; my $part = substr($s, 0, 4); # "Perl"
Offsets start at 0. The length argument is optional.
my $rest = substr($s, 4); # "IsFun"
If the length is omitted,
substr($s, -3); # last 3 characters: "Fun" substr($s, 0, -3);# everything except last 3: "PerlIs"
Negative values are often more readable than equivalent regular expressions.
substr($s, 0, 4) = "Ruby"; # $s is now "RubyIsFun"
Using a regular expression:
my ($head, $tail) = $s =~ /(.{4})(.*)/;
Using
my $head = substr($s, 0, 4); my $tail = substr($s, 4);
When positions are known,
my $line = "key:value"; my $pos = index($line, ":"); my $key = substr($line, 0, $pos); my $val = substr($line, $pos + 1);
For simple separators, this is often easier to read and debug than a regex.
Use
Use a regular expression when structure is variable and pattern matching is required.
Sometimes the simplest tool is the best one.
Knowing its limits: when