Evgeni Bolotin
Evgeni Bolotin

Reputation: 33

How to capture regions flanking string region in Perl?

I'm wondering if there is any Perl function that acts as inverse of substr. If substr selects a part of the string defined by coordinates, this function skips this part and instead captures string parts flanking given coordinates.

It can be just done using substr with coordinates I want for each flank, but I was wondering if there is something built-in for such cases.

Upvotes: 2

Views: 71

Answers (2)

TLP
TLP

Reputation: 67940

This can be handled with substr(), if you add some Perl logic. substr() can be used to delete part of a string by adding an empty string as REPLACEMENT, as denoted in the documentation:

substr EXPR,OFFSET,LENGTH,REPLACEMENT

For example, you can do this:

my $org = "foo bar baz";
my $flank = $org;
my $mid = substr($flank, 4, 3, '');
print "Original: $org\nMid: $mid\nFlank: $flank\n";

Which will print this:

Original: foo bar baz
Mid: bar
Flank: foo  baz

Upvotes: 2

tobyink
tobyink

Reputation: 13674

Easiest and fastest way is probably to use four-parameter substring.

use strict;
use warnings;
use feature 'say';

my $orig    = 'aaabbbccc';

my $middle  = substr( $orig, 3, 3 );

substr( my $flanks = $orig, 3, 3, '/' );

say $orig;    # aaabbbccc
say $middle;  # bbb
say $flanks;  # aaa/ccc

If you don't want the slash in the output, then substr( my $flanks = $orig, 3, 3, '' ).

Upvotes: 3

Related Questions