Beefy Boxes and Bandwidth Generously Provided by pair Networks Russ
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Is it possible to get all tetra words with correct starting position using a better code within a loop?

by ColonelPanic (Friar)
on Nov 22, 2012 at 09:20 UTC ( #1005084=note: print w/ replies, xml ) Need Help??


in reply to Is it possible to get all tetra words with correct starting position using a better code within a loop?

choroba's substr solution is the best for the problem as you have presented it. However, a regex solution could be useful if you will need to introduce other requirements (such as only matching certain characters).

Here is a simple regex solution:

use strict; use warnings; my $string = 'ABCDEFGHIJKL'; print "$1$2 at ".pos($string)."\n" while ($string =~ /(.)(?=(...))/g);

Note that pos($string) returns the position where the next match on $string will start. In this case, that happens to be exactly what you want: it is one greater than the (zero-based) position of the current match, meaning it is the position of the current match with one-based indexing.

Update: as I think about it more, using pos() is probably not the best. It is misleading to use it to refer to the match start position, because that is not what it really means. It works in this case, but the code would break if you changed your regex to match something different. Here is the correct way to get the position of the beginning of your match:

print "$1$2 at ". ($-[0] + 1) ."\n" while ($string =~ /(.)(?=(...))/g) +;

@- is a special variable containing the offset of each subpattern in the previous match. $-[0] will always refer to the beginning of the match (I have added one to give you the one-based position).



When's the last time you used duct tape on a duct? --Larry Wall


Comment on Re: Is it possible to get all tetra words with correct starting position using a better code within a loop?
Select or Download Code
Re^2: Is it possible to get all tetra words with correct starting position using a better code within a loop?
by supriyoch_2008 (Scribe) on Dec 03, 2012 at 06:24 UTC

    ColonelPanic

    Thanks for your suggestions and code. I am sorry for late reply as I did not have access to internet for a few days.

    With deep regards,

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2014-04-21 03:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (490 votes), past polls