开发者

Is for(1) always the same as do in perl?

开发者 https://www.devze.com 2023-03-28 17:36 出处:网络
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 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) and do {}).
  • You can use next, last and redo in them (like for (1)).
  • It doesn't mask $_ (like do {}).

But

  • It can only used where a statement is expected (like for (1), but unlike do {}).

Therefore, { ... } makes more sense than for (1) { ... }, and do { ... } is useful when you want to return a value.


About the same.

  • You can next, last and redo a for loop, but a do is not a loop--including as part of a do-while "loop". So in a non-trivial block, you couldn't be sure. However, this will work:

    do {{
        ...
    }};
    
  • Also do will not automatically set $_ to each member of the list, the way a bare for loop 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号