6

I saw such code:

my $fh = gensym;                                             
open $fh, ">$name" or die "Can't create $name: $!";

which can be written as :

open my $fh, ">$name" or die "Can't create $name: $!";

Is gensym just legacy or still useful in some occasions?

4

1 回答 1

8

遗产。旧模块有时需要全局而不是词法,但仅此而已。

use IPC::Open3 qw( open3 );
open(local *CHILD_STDIN, '<', '/dev/null') or die $!;
my $pid = open3(
   '<&CHILD_STDIN',
   my $CHILD_STDOUT = gensym(),
   my $CHILD_STDERR = gensym(),
   $cmd, @args,
);

再三考虑,您也可以使用它们来创建别名(尽管Data::Alias可以使用词法来做到这一点)。

my $foo;
our $bar; local *bar = \$foo;
$foo = 123; say $bar;  # 123
$bar = 456; say $foo;  # 456
于 2012-12-26T16:54:47.353 回答