in reply to substring problem???

Using a regex is one way to do it:

use strict; use warnings; my $string = 'ABCDEFGHIJKLMNOPQ'; my $tail = 'OPQ'; my $preLen = 4; if ($string =~ /(.{$preLen})$tail/) { print "$1\n"; }

Prints:

KLMN

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: substring problem???
by Limbic~Region (Chancellor) on May 28, 2006 at 15:49 UTC
    GrandFather,
    The problem asked is far more interesting than the real problem actually desired (last 4 chars of a string). I would submit the following as a starting point for the asked problem:
    my $desired = substr($string, index($string, $tail) - 4, 4);
    It has a few obvious flaws but since the desired problem isn't the one asked, I didn't pursue it.

    Cheers - L~R

      I tinkered with that too, and then abandoned it simply because it seemed to require too much status checking. If $tail isn't found in $string, index returns a -1, so you've got to check for that. And then if index() - 4 doesn't exist, you have another problem that will generate a warning, so an out of bounds check needs to be performed as well. I suspect that the substr(..., index()) method is at least as speed efficient as the regexp approach, but it's definately more cumbersome to implement.

      I still like the substr/index approach for its straightforwardness, but regret the implementation will probably tend to look a little unPerlish.


      Dave