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 :)
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.
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.
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.
Almost. In the foreach suffix, you must use $_:
$hash{$_}++ foreach @things;
Or equivalently (since for
and foreach
are aliased for syntax):
$hash{$_}++ for @things;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With