Is it possible to have a foreach loop with a condition in Perl?
I’m having to do a lot of character by character processing – where a foreach loop is very convenient. Note that I cannot use some libraries since this is for school.
I could write a for loop using substr with a condition if necessary, but I’d like to avoid that!
You should show us some code, including the sort of thing you would like to do.
In general, character-by-character processing of a string would be done in Perl by writing
or, if it is more convenient
or
and the latter form can support multiple expressions in the
whilecondition. Perl is very rich with different ways to do the similar things, and without knowing more about your problem it is impossible to say which is best for you.Edit
It is important to note that none of these methods allow the original string to be modified. If that is the intention then you must use
s///,tr///orsubstr.Note that
substrhas a fourth parameter that will replace the specified part of the original string. Note also that it can act as an lvalue and so take an assignment. In other wordscan be written equivalently as
If
splitis used to convert a string into a list of characters (actually one-character strings) then it can be modified in this state and recombined into a string usingjoin. For instancemy @chars = split //, $string;
$chars[0] = ‘X’;
$string = join ”, @chars;
does a similar thing to the above code using
substr.