Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Can we "grow" a string?

by citromatik (Curate)
on Jun 17, 2009 at 08:50 UTC ( [id://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

Replies are listed 'Best First'.
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?

      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

      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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (4)
As of 2024-04-24 01:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found