5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

evalの戻り値

Posted at

eval中でreturnすると、それはevalの戻り値となる。
returnがなかった場合、最後に評価された値がevalの戻り値となる。
dieした場合、評価された値がなかった場合、戻り値は未定義値となる。

case1(); # 2
case2(); # 2
case3(); # not defined
case4(); # not defined
sub case1 {
  my $r = 1;
  $r = eval {
    return 2;
  };
  print defined($r)?$r:"not defined","\n"; # 2
}
sub case2 {
  my $r = 1;
  $r = eval {
    my $a = 3;
  };
  print defined($r)?$r:"not defined","\n"; # 2
}
sub case3 {
  my $r = 1;
  $r = eval {
    my $a = 3;
    die;
  };
  print defined($r)?$r:"not defined","\n"; # not defined
}
sub case4 {
  my $r = 1;
  $r = eval {
  };
  print defined($r)?$r:"not defined","\n"; # not defined
}

要するにサブルーチンとほぼ同じ扱い。

5
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?