Justin
Justin

Reputation: 507

foreach loop with a condition perl?

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!

Upvotes: 0

Views: 3440

Answers (3)

Borodin
Borodin

Reputation: 126772

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

for my $ch (split //, $string) { ... }

or, if it is more convenient

my @chars = split //, $string;
for (@chars) { ... }

or

my $i = 0;
while ($i < @chars) { my $char = $chars[$i++]; ... }

and the latter form can support multiple expressions in the while condition. 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/// or substr.

Note that substr has 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 words

substr $string, 0, 1, 'X';

can be written equivalently as

substr($string, 0, 1) = 'X';

If split is 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 using join. For instance

my @chars = split //, $string; $chars[0] = 'X'; $string = join '', @chars;

does a similar thing to the above code using substr.

Upvotes: 6

ShinTakezou
ShinTakezou

Reputation: 9681

For example:

foreach my $l (@something) {
  last if (condition);
  # ...
}

will exit the loop if condition is true

Upvotes: 2

Joel Berger
Joel Berger

Reputation: 20280

You might investigate the next and last directives. More info in perldoc perlsyn.

Upvotes: 1

Related Questions