Is it possible to write a Perl foreach loop in a single line?
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 kno开发者_如何学编程w that open statement maybe broken :)
Almost. In the foreach suffix, you must use $_:
$hash{$_}++ foreach @things;
Or equivalently (since for
and foreach
are aliased for syntax):
$hash{$_}++ for @things;
You can do:
foreach my $thing (@things) {$hash{$thing}++};
if you want it on one line with a lexically-scoped variable. You can't invert the foreach
and keep the loop-scoped variable.
精彩评论