Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Can we "grow" a string?

by citromatik (Curate)
on Jun 17, 2009 at 08:50 UTC ( #772277=note: print w/ replies, xml ) Need Help??


in reply to Can we "grow" a string?

A simple way to accomplish this could be to use index in combination with substr:

use strict; use warnings; my $str = "ABCDEFGHIJKLMNOP"; my $seed = "FGHI"; my $length = 7; my $slen = length $seed; my $ipos = index $str,$seed; my $lexpand = $slen < $length ? ($length - $slen)/2 : 0; $lexpand = $ipos < $lexpand ? $ipos : $lexpand; print +(substr $str,($ipos - $lexpand),$length),"\n";

This outputs DEFGHIJ as expected. The problem raises when the "expanded" substring reaches the beginning or the end of the reference string.

Update: Solved the limit cases:

"ABCDEFGHIJKLMNOP" "ABC" 7 => ABCDEFG "ABCDEFGHIJKLMNOP" "BC" 7 => ABCDEFG "ABCDEFGHIJKLMNOP" "MN" 7 => JKLMNOP

citromatik


Comment on Re: Can we "grow" a string?
Select or Download Code
Re^2: Can we "grow" a string?
by Anonymous Monk on Jun 17, 2009 at 12:44 UTC
    And, do you think you can put some boundaries too? For example, not let the expanded substring go pass letter C on the left or N on the right?

      Of course you can, but maybe you should take a step back and try to describe what problem you're trying to solve instead. Most of these solutions will involve writing actual code though, so maybe you can show what code you've written so far and where you encounter problems.

        The boundaries will have been calculated in the script before expanding the "small" substring and i will know that I must go say, 3 letters on the right at most and 4 letters on the left at most... Everything else works fine in the code of citromatik.

      I already gave you some working code to start playing with. I'm sure you can modify it to fit your own needs. You only need to understand how the snippet works. If you are confused by any part of the code, don't hesitate to ask again. Please, show me that you are more interested than me in solving your problem!

      citromatik

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://772277]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (8)
As of 2014-12-27 01:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls