#!/usr/bin/perl
use strict;
use warnings;
# Example strings
my $string1 = "ABCDEFderp12345";
my $string2 = "derp";
# Find position of string2 within string1
my $strpos = index($string1, $string2);
# If $strpos is greater than zero (see perldoc index)
if ( $strpos >= 0 ){
# Print remainder of the string
# See perldoc length, perldoc substr
print substr( $string1, ( $strpos + length($string2) ) );
}else{
print "$string2 does not occur within $string1";
}
In the above basic example above we find out if $string2 exists within $string1. If $string2 does not exist within $string1 then index will return -1, otherwise it'll return the position where $string2 occurs. substr can be used to get the text from $string1 after $string2, but we need to add the length of $string2 to the position returned by index as it's offset, because you don't want to include $string2 in what gets printed.
Further recommended reading:
Update: changed gt 0 to >= 0. I wasn't quite awake when I posted. Thanks AnomalousMonk for pointing this out.
Update 2: Slight rewording for clarity. |