Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Change variable multiple times within a single string?

by dd-b (Monk)
on Apr 27, 2013 at 19:37 UTC ( [id://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";

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-03-28 16:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found