http://www.perlmonks.org?node_id=1031007


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";

Replies are listed 'Best First'.
Re^2: Change variable multiple times within a single string?
by GotToBTru (Prior) 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; } }