Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Detecting position of a substring within a string

by graff (Chancellor)
on Mar 20, 2016 at 20:55 UTC ( [id://1158378]=note: print w/replies, xml ) Need Help??


in reply to Detecting position of a substring within a string

Since the matter hinges on knowing what the first and last elements of the string are, I'd be inclined to start by splitting the string into an array, which makes it easy to treat the first and last directly. A capturing split would do it well enough:
#!/usr/bin/perl use strict; use warnings; my %rules = (A => 1,B => 1,C => 0,D => 1); while (<DATA>) { chomp; my @chunks = split( /([ABCD])/ ); my $frst_add = my $last_add = 0; if ( $chunks[1] eq 'D' ) { $frst_add = $chunks[0] * $rules{D}; shift @chunks; shift @chunks; } if ( $chunks[-1] eq 'D' ) { $last_add = $chunks[-2] * $rules{D}; pop @chunks; pop @chunks; } my $s = 0; for ( my $i = 1; $i < @chunks; $i += 2 ) { $s += $chunks[$i-1] * $rules{$chunks[$i]}; } my $s1 = $s + $frst_add; my $s2 = $s + $last_add; $s += $frst_add + $last_add; printf "%s :\ts= %2d s1= %2d s2= %2d\n", $_, $s, $s1, $s2; } __DATA__ 1A2B3C3B1D 2D40A2C1B4D 2D40A2C1B
(Of course, having written this as a stand-alone script, I think it would be better as a subroutine, like what AM did above.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-19 18:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found