Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Change variable multiple times within a single string?

by dd-b (Monk)
on Apr 27, 2013 at 19:37 UTC ( #1031007=note: print w/ replies, xml ) Need Help??


in reply to Change variable multiple times within a single string?

Another variant I haven't seen; processing through the list backwards lets you stop as soon as you find an 'A' or 'B'. (That does mean this won't work if setting that variable is just a proxy for a more complex process with side-effects that really does need to be executed for each letter in the string.)

#! /usr/bin/perl $string="A111B111A111B111"; $yes_or_no="no"; $yes_or_no = ''; for (my $x=1; $x<=length($string); $x++) { my $c = substr($string, -1 * $x, 1); $yes_or_no = "yes" if ($c eq 'A'); $yes_or_no = "no" if ($c eq 'B'); last if $yes_or_no; } print "yes_or_no $yes_or_no\n";


Comment on Re: Change variable multiple times within a single string?
Download Code
Replies are listed 'Best First'.
Re^2: Change variable multiple times within a single string?
by GotToBTru (Vicar) on Apr 29, 2013 at 15:16 UTC
    use warnings; use strict; my $string="A111B111A111B111"; my $yes_or_no="no"; for (reverse(split //, $string)) { if ($_ eq 'A') { $yes_or_no = 'yes'; print "$_ yes_or_no=$yes_or_no\n"; last; } if ($_ eq 'B') { $yes_or_no = 'no'; print "$_ yes_or_no=$yes_or_no\n"; last; } }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2015-09-05 13:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred temperature scale is:










    Results (152 votes), past polls