Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write a Perl foreach loop in a single line?

Tags:

foreach

perl

Is it possible to use a single line foreach loop in Perl?

$hash{$thing}++ foreach my $thing (@things);

I know this is possible with many other commands such as,

die "Invalid file!\n" if (open($Handle, "file.txt"));

I know that open statement maybe broken :)

like image 628
Eric Fossum Avatar asked Aug 16 '11 15:08

Eric Fossum


People also ask

How does foreach loop work in Perl?

A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range.

What is the difference between for loop and for each loop in Perl?

There is no difference. From perldoc perlsyn: The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.

How do I end a foreach loop in Perl?

In many programming languages you use the break operator to break out of a loop like this, but in Perl you use the last operator to break out of a loop, like this: last; While using the Perl last operator instead of the usual break operator seems a little unusual, it can make for some readable code, as we'll see next.


1 Answers

Almost. In the foreach suffix, you must use $_:

$hash{$_}++ foreach @things;

Or equivalently (since for and foreach are aliased for syntax):

$hash{$_}++ for @things;
like image 117
Randal Schwartz Avatar answered Oct 24 '22 01:10

Randal Schwartz