Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks!
I see that there is a lot chit-chatting here on substrings these days... So I figured I post a question myself :
Say you have a string:
$string='ABCDEFGHIJKLMNOPQ';
and you also have the substring :
$substring='OPQ'; How can you print the last 4 characters before the known substring?
That is, I want to print out KLMN... Thanks!

Replies are listed 'Best First'.
Re: substring problem???
by GrandFather (Saint) on May 28, 2006 at 08:14 UTC

    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
      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

Re: substring problem???
by Anonymous Monk on May 28, 2006 at 08:21 UTC
    Oups, I think I got it :
    $wanted_string=substr($string, -4);
    It works ok, I hope it's the correct way to go...
      Yes it is. :-)
Re: substring problem???
by Anonymous Monk on May 28, 2006 at 08:17 UTC
    Hi GrandFather, thanx for the quick reply!
    I apologize, but I think I have made a mistake in my question. Forget about the $substring, I just need to print out the last 4 characters of $string, that is NOPQ...
    Shall I use -1 in my substr function to start counting backwards?
    Thank you!
        No need for the 3rd parameter if you need the whole rest of the string. Just
        substr($string, -4)
        will do.