Is for(1) always the same as do in perl?
for(1){
print 1;
}
do {
print 1;
}
Is it true?
Or开发者_StackOverflow is there any special case these two doesn't equal?
One difference is that for(1) sets $_ to the value of 1, as well:
for(1){
print $_; # prints 1
}
Also, do returns the value of the last command in the sequence:
my $x = do { 1 }; # $x = 1
my $y = for(1){ 1 }; # invalid
You might really be looking for just plain curlies.
{
print 1;
}
It has the following benefits:
- Creates a lexical scope (like
for (1)anddo {}). - You can use
next,lastandredoin them (likefor (1)). - It doesn't mask
$_(likedo {}).
But
- It can only used where a statement is expected (like
for (1), but unlikedo {}).
Therefore, { ... } makes more sense than for (1) { ... }, and do { ... } is useful when you want to return a value.
About the same.
You can
next,lastandredoaforloop, but adois not a loop--including as part of ado-while"loop". So in a non-trivial block, you couldn't be sure. However, this will work:do {{ ... }};Also
dowill not automatically set$_to each member of the list, the way a bareforloop will.
No. They have different compilation properties and have different effects. They are similar in only one dimension, that being that the code they introduce will not be looped over -- something they have in common with other constructs, including bare blocks and (sub {...})->().
Here's an obvious difference: for (LIST) BLOCK is a loop, whereas do BLOCK is an expression. This means that
for (1) {
say "Blurgh"
} unless 1;
doesn't compile, whereas
do {
say "Blurgh"
} unless 1;
does.
加载中,请稍侯......
精彩评论